Learning pagination in Laravel 11 is a valuable skill for any developer working with large datasets. Laravel provides convenient methods for paginating database query results, making it easier to display data in a structured and manageable way. Let’s dive into a practical example tutorial to learn pagination in Laravel 11.
Setting Up Laravel Project
First, ensure you have Laravel installed on your system. If not, you can install it via Composer:
composer create-project --prefer-dist laravel/laravel pagination-example
Navigate to your project directory:
cd pagination-example
Database Configuration
Next, configure your database credentials in the .env
file. Once done, run database migrations to create necessary tables:
php artisan migrate
Creating a Model and Seeder
For demonstration purposes, let’s create a Post
model along with a seeder to populate some sample data:
php artisan make:model Post -m
This command generates a migration file and a model for the Post
entity. Define your schema in the migration file and run migrations:
php artisan migrate
Then, create a seeder to populate the posts
table with sample data:
php artisan make:seeder PostsTableSeeder
Update the seeder with sample data in the run()
method and run the seeder:
php artisan db:seed --class=PostsTableSeeder
Implementing Pagination
Now, let’s implement pagination in a controller to fetch paginated posts:
php artisan make:controller PostController
In the PostController
, fetch paginated posts and pass them to a view:
use App\Models\Post;
public function index()
{
$posts = Post::paginate(10); // Paginate with 10 items per page
return view('posts.index', compact('posts'));
}
Creating Views
Create a view to display paginated posts. Inside resources/views/posts/index.blade.php
, iterate over the posts:
@foreach($posts as $post)
<div>
<h2>{{ $post->title }}</h2>
<p>{{ $post->content }}</p>
</div>
@endforeach
{{ $posts->links() }} <!-- Display pagination links -->
Testing
Finally, test your pagination by navigating to http://localhost:8000/posts
.
Conclusion
In this tutorial, you learned how to implement pagination in Laravel 11. Pagination is essential for managing large datasets efficiently, and Laravel provides convenient methods to achieve this. Practice implementing pagination in your projects to become proficient in handling large amounts of data effectively.