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. Resolving the current page number in the query metadata. Resolving the chunking size ($perPage parameter). Splitting the query results into chunks and get the specific chunk/page that we are after. 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: Resolve current page number in the query metadata. We used the forPage() method to chunk the query results pass...