Laravel 7 Pagination Example with Bootstrap Tutorial

Last updated on by Digamber
In this tutorial, i will share how to create simple pagination in the Laravel 7 application. We will learn to construct simple pagination in laravel 7 application from scratch. We will cover setting up a laravel app, creating model and migrations, creating a controller and connecting controller to routes, and fetch records from the database and bind with pagination() method to show results in smaller sizes using paginate() and links() function.

We will also focus on how to set up a custom path or parameter with laravel pagination and convert pagination results into JSON.

Integrating Pagination in Laravel is very easy because of query builder and Eloquent ORM. It offers a handy and creative way to display database results in smaller pieces. The pagination works well with the Bootstrap CSS framework.

Install Laravel 7 Project

Execute the following command to create a Laravel project.

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

Go inside the project directory.

cd laravel-pagination

Database Configuration

You must have a local server set up on your local development system, and you can use either MAMP or XAMPP. Open the .env file and add your database configuration to make the connection between Laravel and MySQL.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel_db and table_name = migrations and table_type = ‘BASE TABLE’)

If you face above migration error and using MAMP then you must add the below line in .env file.

DB_HOST=localhost;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock

Model and Migrations

Pagination is used to display the large amount of data in chunks, so we need to create a Model that takes care of business logic of our Laravel application. A model refers to the logical structure of the data table in our database.

php artisan make:model Employee -m

Open database/migrations/timestamp_create_employees_table.php file and add the schema.

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('firstname');
        $table->string('lastname');
        $table->string('email')->unique();
        $table->string('dob');
    });
}

Include the following code in the app/Employee.php file to register the schema in the $fillable array.

class Employee extends Model {

    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'dob',
    ];

}

Execute the following command from the command-line tool for database migration.

php artisan migrate

Generate Fake Data using Faker

To display pagination in Laravel, we need to create some fake data so that we can divide that data in small chunks. So, to generate false data, we will use the built-in Laravel package, Faker.

Open the database/seeds/DatabaseSeeder.php file and place the following code.

<?php

use Illuminate\Database\Seeder;

// Import DB and Faker services
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('employees')->insert([
                'firstname' => $faker->firstname,
                'lastname' => $faker->lastname,
                'email' => $faker->email,
                'dob' => $faker->date($format = 'D-m-y', $max = '2010',$min = '1980')
            ]);
        }
    }
}

To generate fake random data in the database declare DB and Faker services at the top, Run a foreach loop and define the range of the data that you have to generate in the database. Define the table name and schema inside the table insert function.

Execute the given command to generate the data.

php artisan db:seed

Now, you can check your employees table in the database with at least 500 new records that you can use for Laravel pagination demo.

Create Controller & Route

Run the command to create the employee controller.

php artisan make:controller EmployeeController

Place the following code in app/Http/EmployeeController.php file.

<?php

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

use App\Employee;

class EmployeeController extends Controller
{
    public function getData(){
      $employeeData = Employee::all();
      return view('home', compact('employeeData'));
    }
}

Create Route

Go to routes/web.php to include the following code to define the route and bind the controller to it.

Route::get('/', 'EmployeeController@getData');

Render Records in View

First, create a blade file resources/views/home.blade.php and place the following code inside of it to render the employee records in Laravel view using Bootstrap Table component.

<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Laravel Pagination Demo</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 mb-5">
                <thead>
                    <tr class="table-success">
                        <th scope="col">#</th>
                        <th scope="col">First name</th>
                        <th scope="col">Last name</th>
                        <th scope="col">Email</th>
                        <th scope="col">DOB</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($employees as $data)
                    <tr>
                        <th scope="row">{{ $data->id }}</th>
                        <td>{{ $data->firstname }}</td>
                        <td>{{ $data->lastname }}</td>
                        <td>{{ $data->email }}</td>
                        <td>{{ $data->dob }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </body>
</html>

Use Pagination in Laravel

Pagination is a way of showing extensive data in a smaller part, Pagination in Laravel is very easy to use; it is integrated with the query builder and Eloquent ORM. Laravel pagination covers limit and offset automatically.

Implementing pagination in laravel is smooth, add the laravel paginate function in the getData() function inside the EmployeeController class. Remove all() and use paginate() and it takes a number as an argument, that number defines the number of results to be shown to the user.

// app > http > controllers > EmployeeController.php

class EmployeeController extends Controller {

    public function getData(){
      $employees = Employee::paginate(8);
      return view('home', compact('employees'));
    }

}

To display the pagination component on the view, we need to add the following code in the home.blade.php file below the table component. Since Laravel pagination goes well with Bootstrap 4 so we do not have to worry about the pagination UI.

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

Pagination in Laravel Example

Here is the final home.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Laravel Pagination Demo</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 mb-5">
            <thead>
                <tr class="table-success">
                    <th scope="col">#</th>
                    <th scope="col">First name</th>
                    <th scope="col">Last name</th>
                    <th scope="col">Email</th>
                    <th scope="col">DOB</th>
                </tr>
            </thead>
            <tbody>
                @foreach($employees as $data)
                <tr>
                    <th scope="row">{{ $data->id }}</th>
                    <td>{{ $data->firstname }}</td>
                    <td>{{ $data->lastname }}</td>
                    <td>{{ $data->email }}</td>
                    <td>{{ $data->dob }}</td>
                </tr>
                @endforeach
            </tbody>
        </table>

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

</html>

Laravel Custom Pagination Parameter

We have created a simple pagination which displays multiple pages of results and creates a url something like this . Basically, it appends a ?page=3.

Append Parameter to Pagination

We can simply add the additional parameter to the pagination url by just using the following code.

{!! $employees->appends(['sort' => 'department'])->links() !!}

Convert Pagination Results To JSON

The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable Interface contract and expose the toJson method. It is straightforward to transform your pagination results into JSON. You may also convert a paginator instance to JSON by returning it from a route or controller action.

Open web.php file and place the following route with paginate function.

Route::get('/home', function () {
    return App\Employee::paginate(5);
});

You can get the JSON data on http://127.0.0.1:8000/home URL.

{
   "current_page":1,
   "data":[
      {
         "id":1,
         "firstname":"Hardy",
         "lastname":"Kuhlman",
         "email":"vcummerata@yahoo.com",
         "dob":"Thu-01-70"
      },
      {
         "id":2,
         "firstname":"Missouri",
         "lastname":"Gaylord",
         "email":"daniel.gene@yahoo.com",
         "dob":"Thu-01-70"
      },
      {
         "id":3,
         "firstname":"Kaela",
         "lastname":"O'Hara",
         "email":"eparker@yahoo.com",
         "dob":"Thu-01-70"
      },
      {
         "id":4,
         "firstname":"George",
         "lastname":"O'Kon",
         "email":"wmurazik@purdy.biz",
         "dob":"Thu-01-70"
      },
      {
         "id":5,
         "firstname":"Chaim",
         "lastname":"Jerde",
         "email":"jerome89@collins.com",
         "dob":"Thu-01-70"
      }
   ],
   "first_page_url":"http:\/\/127.0.0.1:8000\/home?page=1",
   "from":1,
   "last_page":100,
   "last_page_url":"http:\/\/127.0.0.1:8000\/home?page=100",
   "next_page_url":"http:\/\/127.0.0.1:8000\/home?page=2",
   "path":"http:\/\/127.0.0.1:8000\/home",
   "per_page":5,
   "prev_page_url":null,
   "to":5,
   "total":500
}

Run Laravel Application

Execute the following command to start the Laravel pagination demo project.

php artisan serve

You check the app on http://127.0.0.1:8000

Conclusion

Finally, we have completed the Laravel Pagination tutorial with an example. In this tutorial, and we have learned how to work with pagination in Laravel. We got to know about setting up databases, creating models and migrations, creating fake data with faker, creating controller, route and blade view file, and most importantly, we learned to use pagination component in laravel.

We understood the various other methods, such as passing custom parameters with pagination and converting pagination results to JSON.

Thanks for reading, you can get the complete code of this tutorial from GitHub.