Laravel provides an easy-to-use pagination system that allows you to break down large data sets into smaller, more manageable chunks. In Laravel, pagination allows you to divide large result sets into smaller, more manageable chunks, making it easier to display data in a paginated manner. The Laravel Pagination example help you with how to use pagination in Laravel 10 application.
Step 1: Add Route
First, open routes/web.php and update the route just like below.
use App\Http\Controllers\PostController;
Route::get('posts', 'PostController@index');
Step 2: Add Controller
Next, we need to create a new controller using the following command.
php artisan make:controller PostController
Next, open the app/Http/Controllers/PostController.php file and put the following code on it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::paginate(10);
return view('posts',compact('posts'));
}
}
Here, we are using the paginate() method to retrieve 10 posts per page.
Step 3: Create Blade View File
Once you have retrieved the paginated data, you can pass it to your view and display it using Laravel’s built-in pagination links. Here’s an example of how to display the paginated data in a view.
So create a posts blade file inside the resources/view directory. Now open resources/views/posts.blade.php and put the below code on it:
!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Posts 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>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title}}</td>
<td>{{ $post->description}}</td>
</tr>
@endforeach
</tbody>
{{ $posts->links() }}
</table>
</div>
</body>
</html>
Here, we are iterating through each post in the $posts
collection and displaying its title and body. We’re also using the $posts->links()
method to display the pagination links.
The links()
method generates the HTML needed to display the pagination links. By default, Laravel uses a Bootstrap-compatible pagination layout, but you can customize it by passing a view name as a parameter to the links()
method.
That’s it! You have successfully implemented pagination in Laravel application. With pagination, you can easily handle large data sets and improve the performance of your application.