To implement pagination, Laravel provides the paginate()
method that automatically divides your query results into pages.
Example: Basic Pagination Setup
use App\Models\Post;
public function index()
{
// Paginate data with 10 items per page
$posts = Post::paginate(10);
return view('posts.index', compact('posts'));
}
paginate(10)
method fetches 10 posts per page.In your Blade view, you can loop through the paginated data and display pagination links using the links()
method.
Example: Displaying Posts in the View
@foreach ($posts as $post)
<p>{{ $post->title }}</p>
@endforeach
<!-- Display pagination controls -->
{{ $posts->links() }}
{{ $posts->links() }}
automatically generates the pagination links (previous, next, etc.).Laravel allows you to customize the pagination view. You can publish the pagination views to modify the structure.
Example: Customizing Pagination View
php artisan vendor:publish --tag=laravel-pagination
To allow users to choose how many items to display per page, you can pass a dynamic value to the paginate()
method.
Example: Dynamic Items per Page
$perPage = $request->input('perPage', 10); // Default to 10 items per page
$posts = Post::paginate($perPage);
Laravel automatically retains query parameters when paginating. You don’t need to manually pass them.
Example: Pagination with Query Parameters
// URL: /posts?page=2&search=example
$posts = Post::where('title', 'like', '%'.$search.'%')->paginate(10);
For simpler pagination without page numbers (just "Next" and "Previous" links), you can use simplePaginate()
.
Example: Simple Pagination
$posts = Post::simplePaginate(10);
If you need to customize pagination URLs, you can modify the pagination configuration in config/pagination.php
.
Example: Custom URL Format
$posts = Post::paginate(10)->withPath('/custom/posts');
/custom/posts?page=2
.Laravel's pagination features are powerful and flexible, allowing developers to paginate data easily, display pagination controls, and customize the experience for users. Whether you need simple pagination, customizable links, or dynamic items per page, Laravel offers solutions that are both intuitive and effective.