To create pagination in Laravel, you can use the “paginate()” method on the query builder or an Eloquent query. The paginate() method sets the proper limit and offsets based on the current page that the user is viewing. Laravel’s paginator is out of the box with the query builder and Eloquent ORM and includes database results. The HTML generated by a paginator is compatible with Bootstrap 5.
Here are the steps to create Pagination in Laravel:
Step 1: Install Laravel
composer create-project laravel/laravel laravelpagination --prefer-dist
Set up a database in the .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=larapagination DB_USERNAME=root DB_PASSWORD=root
The next step is to go to the terminal and hit the following command.
php artisan migrate
Step 2: Generating fake data in the database
Go to the database >> seeders >> DatabaseSeeder.php and add the following lines of code.
public function run(): void { User::factory(100)->create(); }
Now type the following command to create the fake data.
php artisan db:seed
Now you can see in the database and the users’ table that 100 rows have been added.
The db:seed command runs this file called DatabaseSeeder.php.
Step 3: Display the data to the front end.
First, we need to create a DataController.php file by typing the following command.
php artisan make:controller DataController
Now, create one function called getUsers().
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class DataController extends Controller { public function getUsers() { $users = User::all(); return view('index', compact('users')); } }
Define the route inside a web.php file.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\DataController; Route::get('/', function () { return view('welcome'); }); Route::get('users', [DataController::class, 'getUsers'])->name("datacontroller.index");
Create one file inside the resources >> views folder called index.blade.php.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Users Data</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>User List</h1> <!-- Added a header for clarity --> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> @forelse($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> @empty <tr> <td colspan="3">No users found.</td> <!-- Handling the case where no users are found --> </tr> @endforelse </tbody> </table> </div> </body> </html>
Start the development server with the following command.
php artisan serve
Move to the browser and hit this URL: http://127.0.0.1:8000/users
It displays all the rows, which is what we want. We want to paginate the data. So let us do that.
Step 4: Paginating Eloquent Results
We need to use the paginate() function provided by the Eloquent model. So replace the method of all() to paginate() and pass the number of rows as a parameter.
public function getUsers() { $users = User::paginate(10); return view('index', compact('users')); } }
We need to display the pagination web component at the front end. As discussed earlier, Laravel’s pagination object works well with Bootstrap 5.
Now, add the following code into the app >> providers >> AppServiceProviders.php file.
use Illuminate\Pagination\Paginator; public function boot(): void { Paginator::useBootstrapFive(); }
So, we need to add the following code to the table component inside the index.blade.php file.
{{ $users->links() }}
Our whole index.blade.php file looks like this.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Users Data</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <div class="container"> <h1>User List</h1> <!-- Added a header for clarity --> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> @forelse($users as $user) <tr> <td>{{ $user->id }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> @empty <tr> <td colspan="3">No users found.</td> <!-- Handling the case where no users are found --> </tr> @endforelse </tbody> </table> {{ $users->links() }} </div> </body> </html>
Converting Pagination Results To JSON
So write the following code inside a web.php file.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\DataController; use App\Models\User; Route::get('/', function () { return view('welcome'); }); //Route::get('users', [DataController::class, 'getUsers'])->name("datacontroller.index"); Route::get('users', function () { return User::paginate(10); });
It will return as JSON-format data.
You can use this object and its metadata on the front end to create pagination as per your requirement.
That’s it.
Pablo
Hi! Krunal
I have followed several of your examples and they have been of a lot of help. But this one does not run from the beginning.
First, I got: “Symfony\Component\Debug\Exception\FatalThrowableError : Class ‘Faker’ not found”
Then, I add at the beginning: “use Faker\Generator as Faker;”
But I got: “Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined method Faker\Generator::create()”
Besides that, I have not created “HomeController.php”
Can you give me a help, about it, please.
Pablo
Problem solved!
Looking into the subdirectory vendor. I found that I should use “Faker\Factory::create();” instead of “Faker::create();” in the file ‘database/seeds/DatabaseSeeder.php’. For HomeController.php, I just have to created with “php artisan make:controller HomeController”. Everything else is OK. Thanks!
Trabajo Enlinea
great job! This was really helpful!
Pardeep Kumar
Nice tutorial
vinu
Display the data to the frontend.
dicaredo
You have a github link?
kaka isaac
Hi i get this error call to undefined function links() in the view
Call to undefined method AppEmployee::links() (View: /home/izackk/Desktop/Payroll/resources/views/employee/index.blade.php)
Here is my controller
public function index()
{
//
$employee = Employee::paginate(1);
return view(“employee.index”)->with(’employee’, $employee);
}
my view
@extends(‘layouts.app’)
@section(‘content’)
@if(count($employee)>0)
Name
Gender
Phone
Address
TIN
Profile Image
Action
@foreach($employee as $employee)
{{ $employee->name }}
{{ $employee->gender }}
{{ $employee->phone }}
{{ $employee->address }}
{{ $employee->TIN }}
{{ $employee->profileimage }}
id }}”>EDIT
id }}”>DELETE
@endforeach
{{ $employee->links() }}
@else
Employee not found
@endif
@endsection
heber
Krunal,
Nice, great post. Just a question:
Is possible to add some information on paginations information? For example i’d like to add Request data given.
Алекс
Thanks!!!!