How to use Laravel Pagination with examples

If you have to display high volume of data in Laravel, it is always better to display them in multiple pages. Laravel gives very 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 a html table. We will use Laravel Pagination along with Bootstrap and custom styles to show how pagination works in Laravel.

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

Here, I want to display 10 records per page. In the view just use below page links after displaying data in a table:

Laravel pagination

Step1 - Create a Laravel project

Let us create a project in laravel 10. Make sure you have composer and PHP installed in your system. I have given the project name as lara_pagination. Use create-project command.

This will create a folder named "lara_pagination" under the folder where you run the above command.

Step 2 - MySQL Migration and create test data using Laravel factory

Update .env file for database details. I am using MySQL database named 'lara_demo', so I updated the file as below:

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

Now, run databaase seeder to create the rows:

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

pagination in laravel

Step 3 - Laravel Controller

We will create UserController with index() method in it to select data from users table using Laravel pagination.

laravel pagination example

Controller will have below methods:

index() method

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

We have used Laravel pagination to display 10 rows per page.

Routes

Step 4 - Laravel blade views

We have one view for listing the users along with the layouts.

resources/views/layouts/header.blade.php

resources/views/layouts/master.blade.php

resources/views/index.blade.php

Stylesheet is given below:

public/css/style.css

Step 5 - Update AppServiceProvider for Bootstrap 5 Pagination

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

Add Paginator library as use Illuminate\Pagination\Paginator;

Step 6 - Test the application

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

From browser start localhost:8000. It should display data in pages. Since there are 100 rows so there will be 10 pages.

laravel pagination style