The PaginationUtil
in the LaraUtilX
package provides functionality for paginating collections.
paginate(array $items, int $perPage, int $currentPage, array $options = []): LengthAwarePaginator
: Paginates a collection.paginateQuery($query, int $perPage, ?int $page = null, array $options = []): LengthAwarePaginator
: Paginates an Eloquent or Query Builder instance, automatically resolving the page from the request if not provided.Paginate Collection:
To paginate a collection, use the paginate
method:
use LaraUtilX\Utilities\PaginationUtil;
$items = [...]; // Your array of items to paginate
$perPage = 10; // Number of items per page
$currentPage = 1; // Current page number
$paginator = PaginationUtil::paginate($items, $perPage, $currentPage);
This example paginates the given array of items with 10 items per page and retrieves the first page of results.
Paginate Query or Eloquent Builder:
To paginate a database query or Eloquent builder, use the paginateQuery
method:
use LaraUtilX\Utilities\PaginationUtil;
// For Eloquent or Query Builder
$query = User::where('active', true); // Example query
$perPage = 15;
// Optionally, you can specify the page or let it default to the request's 'page' parameter
$paginator = PaginationUtil::paginateQuery($query, $perPage);
You can also pass custom options to append to the pagination links:
$options = [
'search' => 'john',
'sort' => 'desc',
];
$paginator = PaginationUtil::paginateQuery($query, $perPage, null, $options);
Options: You can customize pagination options by passing an array of options as the fourth parameter:
$options = [
'path' => '/custom-path', // Customize the path for the paginator links
'fragment' => 'page', // Customize the fragment identifier for the paginator links
// Add more options as needed
];
$paginator = PaginationUtil::paginate($items, $perPage, $currentPage, $options);
The utility returns a LengthAwarePaginator instance, which provides paginated data along with pagination metadata.
Success Result:
Failure Result:
This utility simplifies the process of paginating collections, providing a convenient way to manage large datasets in chunks.