Create Custom Pagination in Laravel: A Step-by-Step Guide

AuthorSumit Dey Sarkar

Pubish Date08 Apr 2023

categoryLaravel

In this tutorial we will learn how to create custom pagination in laravel.

 

Create Custom Pagination in Laravel

In Laravel, you can create custom pagination using the LengthAwarePaginator class.

The steps to implement custom pagination in Laravel are as follows:

 

Step 1 - The data you want to paginate must first be retrieved from the database.

 

Step 2 - Next, you must make an instance of the LengthAwarePaginator class and supply the data, the amount of items you wish to display per page, and the current page number.

use Illuminate\Pagination\LengthAwarePaginator;

$itemsPerPage = 10; // change this to your desired number
$currentPage = request()->query('page', 1); // get the current page number from the query string or default to 1
$data = MyModel::paginate($itemsPerPage, ['*'], 'page', $currentPage);
$customPaginator = new LengthAwarePaginator($data->items(), $data->total(), $data->perPage(), $data->currentPage());

Here, we are passing the data, the total number of items, the number of items per page, and the current page number to the LengthAwarePaginator constructor.

 

Step 3 - Now, you can render the pagination links using the links() method of the LengthAwarePaginator instance.

{{ $customPaginator->links() }}

This will generate the pagination links for your custom pagination.

 

Step 4 - Finally, you can display the paginated data in your view using the items() method of the LengthAwarePaginator instance.

@foreach ($customPaginator->items() as $item)
    // display each item here
@endforeach

 

That's it! You have created custom pagination in Laravel.

Comments 0

Leave a comment