Implementing pagination in Laravel is relatively straightforward, thanks to Laravel’s built-in support for pagination. Laravel makes it easy to retrieve a set of records from a database table and display them in smaller, more manageable chunks on your web page. Here are the steps to implement pagination in Laravel:
1. Install Laravel (If not already installed): If you haven’t already set up a Laravel project, you can do so using Composer:
composer create-project --prefer-dist laravel/laravel your-project-name
2. Create a Database and Model:
You'll need a database table and a corresponding Eloquent model to paginate data. You can create a migration to create a table and then generate a model using Laravel's Artisan command-line tool:
php artisan make:migration create_table_name
After creating the migration, don’t forget to define the table schema in the generated migration file and run the migration:
php artisan migrate
3. Create Routes:
Define routes in your `routes/web.php
` file to handle the pagination:
Route::get('/items', 'ItemController@index');
4. Create a Controller:
Create a controller (e.g., ItemController
) to handle the pagination logic:
php artisan make:controller ItemController
5. Implement Pagination in the Controller:
In your controller, retrieve the data you want to paginate and use the paginate
method to split it into smaller portions. For example:
use App\Models\Item; // Import your model
public function index()
{
$items = Item::paginate(10); // Paginate by 10 items per page
return view('items.index', compact('items'));
}
6. Create Views:
Create views to display the paginated data. You can use the links
method to generate pagination links in your Blade template:
@foreach ($items as $item)
<!-- Display item data here -->
@endforeach
{{ $items->links() }}
The links method generates the pagination links at the bottom of the list.
7. Styling (Optional):
You can customize the appearance of the pagination links by modifying the CSS classes or using a CSS framework like Bootstrap.
8. Test:
- Visit the URL you defined in your routes (e.g.,
/items
) to see the paginated data in action.
That’s it! You’ve successfully implemented pagination in a Laravel application. You can adjust the number of items per page by changing the argument passed to the paginate
method in your controller.