Custom pagination example in laravel

The main of this blog is to create simple custom pagination that will work with a database.

For your better understanding, we have divided the program into some parts.

  • Create Model And Migrations
  • Create Controller
  • Create Blade File
  • Adding Custom Pagination
  • Adding Routes
  • Test Our Application

let’s assume you have a Laravel application. If you don’t have any application then create a new application and try further steps into it.

Create Model and Migrations

In this example, we will display pagination data from the database so we need to create a database table. In Laravel, we need to create migration for creating database tables and models to access those data in effective ways.

To create a model and migration you need to enter the below command into a terminal :

php artisan make:model Data -mfs

Here, we have to pass additional parameters mfs m is for migrations, F is for factory, and S is for seeder. Those files will be used for generating dummy data in a database.

Let’s make changes in all files one by one.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDataTable extends Migration
{
    public function up()
    {
        Schema::create('data', function (Blueprint $table) {
            $table->id();
            $table->string('name');  //add this line
            $table->text('address'); //add this line
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('data');
    }
}

Now, we have to migrate our database. Enter the below command into a terminal :

php artisan migrate

This command will generate Data in our database. let’s add some dummy data into our database using factory and seeder.

database\factories\DataFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class DataFactory extends Factory
{
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'address' => $this->faker->address()
        ];
    }
}

database\seeder\DataSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Data;
use Illuminate\Database\Seeder;

class DataSeeder extends Seeder
{
    public function run()
    {
        Data::factory()->count(100)->create();
    }
}

This alteration will apply logic for creating 100 dummy data while you run the below command.

php artisan db:seed --class=DataSeeder

Create Controller

Let’s create a controller that will handle the operation for pagination and return view with data.

php artisan make:controller DataController

This command will create DataController.php. The new controller has only one method which will get all data from our model and return it to view. Let’s make modifications for that :

app\Http\Controller\DataController.php

<?php

namespace App\Http\Controllers;

use App\Models\Data;
use Illuminate\Http\Request;

class DataContoller extends Controller
{
    public function index()
    {
        $data = Data::paginate(10);
        return view('data', compact('data'));
    }
}

Adding Routes

In this step, we just need to define a route. For that make the following changes to the route file. Here, we have created /view-data route which will call the index method of DataController.

routes\web.php
<?php

use App\Http\Controllers\DataController; //import
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
Route::get('/view-data', [DataController::class,'index']); //add this line

Adding Custom Pagination

For Custom pagination either we can create a new view file that will handle pagination or modify existing views.

We can use default files for modification but in some cases, if you want to use both paginations then you need to create a new file that will handle our custom pagination request. For that create a file anywhere under the views directory with .blade.php extension.

resources\views\custom_pagination.blade.php

<ul class="pagination">
    @if ($paginator->onFirstPage())
        <li class="disabled"><span>&laquo;</span></li>
    @else
        <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">&laquo;</a></li>
    @endif

    @foreach ($elements as $element)
        @if (is_string($element))
            <li class="disabled"><span>{{ $element }}</span></li>
        @endif

        @if (is_array($element))
            @foreach ($element as $page => $url)
                @if ($page == $paginator->currentPage())
                    <li class="active"><span>{{ $page }}</span></li>
                @else
                    <li><a href="{{ $url }}">{{ $page }}</a></li>
                @endif
            @endforeach
        @endif
    @endforeach

    @if ($paginator->hasMorePages())
        <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a></li>
    @else
        <li class="disabled"><span>&raquo;</span></li>
    @endif
</ul>

In this step, we will create a view that will display data that passed through a controller to the user in table format with pagination links. For data display, we will use Bootstrap to style data and a table to display formatted data. Let’s make changes to the view.

resource\views\data.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <style>
            ul{
                float: right;
            }
            li {
                margin-left: 20px;
            }
        </style>
    </head>
    <div class="container">
        <h1>Laravel Pagination Example - Codewolfy.com</h1>
        <table class="table table-bordered mt-5">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                @foreach($data as $key => $value)
                    <tr>
                        <td>{{ $value->id}}</td>
                        <td>{{ $value->name}}</td>
                        <td>{{ $value->address}}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>

       {!! $data->links('custom_pagination') !!}
</div>
    </body>
</html>

Testing Our Application

php artisan serve

Open the below URL in your browser :

http://127.0.0.1:8000/view-data

In output, it will display the names and addresses of 10 people. Here it displays custom links for pagination which we applied to our view.