In this tutorial you will learn Laravel Pagination Example with Bootstrap. Pagination is a crucial feature for managing large datasets in web applications. Laravel provides a convenient and powerful pagination system that allows you to split data into smaller chunks and display it in a user-friendly manner. Let’s walk through an example of how to use pagination in Laravel application.
Step 1: Add Route
First, add a route in your routes/web.php file to get data using paginator in Laravel.
Route::get('users', 'UserController@index');
Step 2: Create Controller
Next, create a controller using the following command:
php artisan make:controller UserController
Next, open the newly created controller app/Http/Controllers/UserController.php and put the below code on it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::paginate(10);
return view('users',compact('users'));
}
}
Step 3: Create Blade File
In this step, we need to create users blade file and put bellow code with {{ $users->links() }}
so it will generate pagination automatically. Let open the resources/views/users.blade.php file and update the below code on it;
!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Users Data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name}}</td>
<td>{{ $user->email}}</td>
</tr>
@endforeach
</tbody>
{{ $users->links() }}
</table>
</div>
</body>
</html>
Now you can check your pagination to run below command.
php artisan serve
open your browser and check localhost http://localhost:8000/users.
That’s it! You have now implemented pagination in Laravel. The paginated data will be displayed in your view, and the pagination links will allow users to navigate through the different pages of data.