How to Create Pagination in Laravel 8 with Bootstrap

This tutorial is an ultimate elixir if you are a novice developer and looking for building the pagination component in Laravel application using Bootstrap 4. We will help you create the pagination in the Laravel 8 application from the absolute beginning.

Not just that, you will also learn to configure a custom path and get aligned with laravel pagination to convert pagination results into JSON (JavaScript Object Notation) format.

Pagination is a significant user interface element that helps organize the large dataset for site visitors; it arranges and divides the content and displays in a limited amount.

The developing component in web application becomes easy when you get a ready-made solution; it gives a good start for you, and atleast you have an idea from where to start.

Consequently, in this tutorial, you will learn to create a laravel application; from starting, you will have a basic idea of the following:

  • Adding database details
  • Creating a model
  • Running migrations
  • Creating dummy records using faker library
  • Creating controllers & route
  • Displaying the data with laravel blade view & Bootstrap 4
  • Using pagination in laravel application
  • Creating a custom parameter for pagination
  • Adjoining parameter to pagination
  • Converting pagination results to JSON

Let’s start building the Laravel 8 pagination feature:

Create Laravel Project

First, you need to create a Laravel app.

composer create-project laravel/laravel --prefer-dist laravel-pagination-example

Add Database Details

You need to include database name, username and password in .env, not only but also start your local development server such as MAMP or XAMPP.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=

Create Model & Run Migration

As far as fetching data from database is concerned you need to have a model which contains the table schema, therefore run given command to create a Student model.

php artisan make:model Student -m

Add given below code in database/migrations/timestamp_create_students_table.php file.

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('dob');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

On the other hand add the given code in the app/Models/Student.php file:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'dob',
    ];

}

Run the migration to insert values in the database:

php artisan migrate

Create Dummy Records with Faker

Additionally, you need to add the dummy records in the database to display in the table to get managed by pagination.

You are about to see Faker package in action to generate the fake records.

Add the given below code in the database/seeds/DatabaseSeeder.php:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

    	foreach (range(1,500) as $index) {
            DB::table('students')->insert([
                'name' => $faker->name,
                'email' => $faker->email,
                'dob' => $faker->date($format = 'D-m-y', $max = '2020',$min = '1990')
            ]);
        }
    }
}

Now, you can generate the dummy records:

php artisan db:seed

Generate & Setting Up Controller

Now, you need to generate a new student controller.

php artisan make:controller StudentController

Add the given below code in app/Http/StudentController.php:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    // Display pagination
    public function getStudents(){
        $student = Student::paginate(10);
        return view('welcome', compact('student'));
    }
}

The getStudents() function contains the logic to fetch student records from the database, the student model is aligned with the paginate() method and manifest only 10 records with the help pagination package.

Create Route

Now, you need to define the route in routes/web.php which will get results on GET request:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [StudentController::class, 'getStudents']);

Display Records in Blade View

Besides, head over to resources/views/welcome.blade.php file and replace with the given below code:

<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        
        <title>Laravel Pagination Examle</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    </head>

    <body>
        <div class="container mt-5">
            <table class="table table-bordered">
                <thead>
                    <tr class="table-primary">
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Date of Birth</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($student as $item)
                    <tr>
                        <th scope="row">{{ $item->id }}</th>
                        <td>{{ $item->name }}</td>
                        <td>{{ $item->email }}</td>
                        <td>{{ $item->dob }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </body>
</html>

Using Laravel Pagination

Next, head over to app/Providers/AppServiceProvider.php file and import and use Paginator::useBootstrap() in the boot() method:

<?php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

Provided paginate() method in controller lets you integrate pagination in laravel, just add the below code in welcome.blade.php file:

<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        
        <title>Laravel Pagination Examle</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    </head>

    <body>
        <div class="container mt-5">
            <table class="table table-bordered">
                <thead>
                    <tr class="table-primary">
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Date of Birth</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($student as $item)
                    <tr>
                        <th scope="row">{{ $item->id }}</th>
                        <td>{{ $item->name }}</td>
                        <td>{{ $item->email }}</td>
                        <td>{{ $item->dob }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>

            <div class="d-flex justify-content-center">
                {!! $student->links() !!}
            </div>            
        </div>
    </body>
</html>

Define Custom Parameter in Laravel Pagination

In the previous example, we created a simple pagination which produces URL something like this ?page=4. However, you will learn to create a custom parameter that you are abut to append into pagination.

<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        
        <title>Laravel Pagination Examle</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    </head>

    <body>
        <div class="container mt-5">
            <table class="table table-bordered">
                <thead>
                    <tr class="table-primary">
                        <th scope="col">#</th>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Date of Birth</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($student as $item)
                    <tr>
                        <th scope="row">{{ $item->id }}</th>
                        <td>{{ $item->name }}</td>
                        <td>{{ $item->email }}</td>
                        <td>{{ $item->dob }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>

            <div class="d-flex justify-content-center">
                {!! $student->appends(['sort' => 'science-stream'])->links() !!}
            </div>            
        </div>
    </body>
</html>

Now, pagination URL will become like this:

http://127.0.0.1:8000/?sort=science-stream&page=4

Transform Pagination Data into JSON

In the last example, you will see how to transform pagination results into JSON through the Jsonable.

Define the route for converting pagination records into JSON in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [StudentController::class, 'getStudents']);

// Transform to JSON
Route::get('/to-json', function () {
    return App\Models\Student::paginate(4);
});

See the converted pagination data into JSON on http://127.0.0.1:8000/to-json path.

{
  "current_page": 1,
  "data": [
    {
      "id": 1,
      "name": "Lauretta Kub",
      "email": "[email protected]",
      "dob": "Thu-01-70",
      "created_at": null,
      "updated_at": null
    },
    {
      "id": 2,
      "name": "Mr. Sigrid Sanford Sr.",
      "email": "[email protected]",
      "dob": "Thu-01-70",
      "created_at": null,
      "updated_at": null
    },
    {
      "id": 3,
      "name": "Miss Anabelle Langosh",
      "email": "[email protected]",
      "dob": "Thu-01-70",
      "created_at": null,
      "updated_at": null
    },
    {
      "id": 4,
      "name": "Melisa Schultz",
      "email": "[email protected]",
      "dob": "Thu-01-70",
      "created_at": null,
      "updated_at": null
    }
  ],
  "first_page_url": "http://127.0.0.1:8000/to-json?page=1",
  "from": 1,
  "last_page": 125,
  "last_page_url": "http://127.0.0.1:8000/to-json?page=125",
  "links": [
    {
      "url": null,
      "label": "&laquo; Previous",
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=1",
      "label": 1,
      "active": true
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=2",
      "label": 2,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=3",
      "label": 3,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=4",
      "label": 4,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=5",
      "label": 5,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=6",
      "label": 6,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=7",
      "label": 7,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=8",
      "label": 8,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=9",
      "label": 9,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=10",
      "label": 10,
      "active": false
    },
    {
      "url": null,
      "label": "...",
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=124",
      "label": 124,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=125",
      "label": 125,
      "active": false
    },
    {
      "url": "http://127.0.0.1:8000/to-json?page=2",
      "label": "Next &raquo;",
      "active": false
    }
  ],
  "next_page_url": "http://127.0.0.1:8000/to-json?page=2",
  "path": "http://127.0.0.1:8000/to-json",
  "per_page": 4,
  "prev_page_url": null,
  "to": 4,
  "total": 500
}

Test Laravel Pagination

Run the app to test pagination in laravel:

php artisan serve
http://127.0.0.1:8000

Create Pagination in Laravel 8 with Bootstrap

Summary

Pagination is a UI mechanism that helps to show the extensive records into limited quantity, and we saw in this simple Laravel pagination tutorial on how to create pagination with custom parameter.

Download code: https://github.com/remotestack377/LaravelPaginationExample