Pagination Utility

The PaginationUtil in the LaraUtilX package provides functionality for paginating collections.

Methods

  1. paginate(array $items, int $perPage, int $currentPage, array $options = []): LengthAwarePaginator: Paginates a collection.
  2. 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.

Usage

  1. 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.

  2. 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);
  3. 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);

Result

The utility returns a LengthAwarePaginator instance, which provides paginated data along with pagination metadata.


Success Result:

  • The paginator instance contains the paginated data along with metadata such as the total number of items, current page number, items per page, and more.

Failure Result:

  • If there are no items to paginate, the paginator instance will still be created with an empty dataset.

This utility simplifies the process of paginating collections, providing a convenient way to manage large datasets in chunks.