Laravel: How to Paginate Collection

 

Understanding how Laravel Paginator works

If we dive into Laravel’s query builder source code:

I will briefly explain what Laravel is doing here line by line.

  1. Resolving the current page number in the query metadata.
  2. Resolving the chunking size ($perPage parameter).
  3. Splitting the query results into chunks and get the specific chunk/page that we are after.
  4. Generate a paginator response which includes the pagination metadata and result chunk.

As seen in step 3, Laravel collection class provides a sweet forPage() method, which does the chunking and page retrieving for the paginator. Hmm…Let’s see if we can utilise that.

Creating a helper class

Let’s create our own collection helper class as shown below.

I borrowed the paginator function from Laravel’s query builder class to return the same pagination response as Eloquent. Here’s what happening in our paginate method:

  1. Resolve current page number in the query metadata.
  2. We used the forPage() method to chunk the query results passed into the function. Then we return a pagination response with the other metadata, e.g total, pageSize and etc.

That’s it. We can now use this helper function wherever in our app.

Usage:

  1. Sorting mutator

If you have included a mutator in your Eloquent model, you may want to sort query results by it. Eloquent doesn’t support mutator sorting, as mutator attributes are created after the query is completed. Good news is we can achieve this by leveraging our helper class that we just created.

Let’s say we have a full_name mutator in our customer model which combines first_name and last_name together. And we want to sort our query result by full_name. We can achieve this by:

// we use the sortBy method from collection class
$results = Customer::all()->sortBy('full_name');

$pageSize = 20;
$paginated = CollectionHelper::paginate($results, $pageSize);

2. Paginate non eloquent results

They could be merged results obtained from multiple API resources. This is especially common when we are integrating multiple app services together.

Comments

Popular posts from this blog

How to Install and Use Wine on Ubuntu 20.04

Laravel 8 Redis setup on Windows with xampp