How to use Laravel Pagination with examples

If many rows of data are to be displayed in a web page, it is always better to display them in multiple pages. It gives a better user experience and improves performance as we do not need to display the full list at once. Laravel provides a simple pagination feature for the developers to display data in multiple pages.

In this topic, we will see how to display Laravel pagination while displaying the data in an html table. We will use the Laravel Pagination with Bootstrap and custom styles to show how pagination works in Laravel.

To display pagination, use the paginate() method while selecting data in the Controller. Like below:


public function index()
{
    $data = User::latest()->paginate(10);
    return view('index',compact('data'));
}

Here, we want to display 10 records per page. In the view use $data->links() after displaying data in the html table.


  {{ $data->links() }}

Pagination example in laravel

Create a Laravel project

We will create a Laravel 10 project.


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

You will see a folder named "lara_pagination" in the same folder from where you run the create-project command.

MySQL Migration and create test data using Laravel factory

Update .env file for the database details. We will use MySQL database and our database name is "lara_demo", we will update the .env file as below:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lara_demo
DB_USERNAME=root
DB_PASSWORD=

Now, run the database migration to create the tables. Run the below command from the terminal:


php artisan migrate

We will use Laravel's default "User" Model and "users" tables for this topic. We have to create some test data using Laravel Factory and Seeder to populate the "users" table. We will display the data in the view using the pagination library. We can use UserFactory.php under database/factories, it comes along with the Laravel project. We just need to update DatabaseSeeder.php under the database/seeders folder. Let us uncomment the first line in the run() method of DatabaseSeeder.php and update 10 to 100. We want to create 100 rows in the "users" table.


public function run(): void
{
    \App\Models\User::factory(100)->create();

    // \App\Models\User::factory()->create([
    //     'name' => 'Test User',
    //     'email' => 'test@example.com',
    // ]);
}

Now, run the database seeder to create the rows:


php artisan db:seed

You can see there are 100 rows created in the "users" table.

pagination in laravel

Laravel Controller

We will create a controller named "UserController" and will use the index() method to select data from the "users" table using Laravel pagination. Use the below command to create the controller.


php artisan make:controller UserController

index() method

This method selects all data from the User model and loads the index view.


public function index()
{
    $data = User::latest()->paginate(10);
    return view('index',compact('data'));
}

We have used paginate(10) to display 10 rows per page.

Routes

We will use the below route:


Route::get('/', [UserController::class, 'index'])

Laravel blade views

We have one view for listing the users in an HTML table. We will have a header and a master layout.

resources/views/layouts/header.blade.php


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Laravel Pagination</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
  <meta name="_token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="{{ asset('css/style.css') }}" />
</head>

resources/views/layouts/master.blade.php


@include('layouts.header')
<body>
  @yield('main-content')
</body>
</html>

resources/views/index.blade.php


@extends('layouts.master')
@section('main-content')
    <h1>Laravel Pagination</h1>
    <div class="container">
        <h4>List of Users</h4>
        <div class="table-responsive">
            <table class="table table-striped table-bordered mt-5">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Created At</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($data as $index => $row)
                        <tr>
                            <td>{{ $index + 1 }}</td>
                            <td>{{ $row->name }}</td>
                            <td>{{ $row->email }}</td>
                            <td>{{ $row->created_at }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6">No Users Found</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
            {{ $data->links() }}
        </div>
@endsection

Stylesheet is given below:

public/css/style.css


* {box-sizing: border-box;
}
body {
  margin: 0;
  font-family: Helvetica, sans-serif;
  font-size:14px;
}
h1,h4{
  text-align: center;
  margin-bottom: 20px;
  margin-top: 10px;
}

.container{
    min-height: 600px;;
}

table>thead{
  background-color:#2b5171;
  color:#fff;
}

Update AppServiceProvider for Bootstrap 5 Pagination

Open AppServiceProvider.php under app/Providers and update the boot() method to use Bootstrap 5 pagination. See the below code:


public function boot(): void
  {
      Paginator::useBootstrapFive();
  }

Add Paginator library as use Illuminate\Pagination\Paginator; in this AppServiceProvider.php

Test the application

From the project root, start the php development server using the artisan command:


php artisan serve

From the browser start localhost:8000. It should display data with page numbers. Since there are 100 rows in the table, there will be 10 pages.

pagination in laravel

Post a Comment

Save my Name and Email id for future comments