How to customize the ‘page’ key name in ‘Laravel Pagination’.

David Yartey
3 min readAug 31, 2019

--

Photo by BENCE BOROS on Unsplash

I was once tasked to build an API with Laravel for an external team of developers to work with. Through this project, I learned a little more about pagination which I’d like to share.

Now you may already know how Laravel pagination works.

Laravel pagination with two(2) records per page.

This returns a paginated response with two(2) records per page and some metadata. See the below image.

Paginated response with two(2) records per page and some metadata.

In the above image, a link to the next page ‘next_page_url’ can be seen as part of the response. Now if you take a closer look at the link, you would notice a query string ‘page=2’ where the number of records per page is specified. There are times when you may need to change this key name. Personally, it was when I had to return a response with two separate paginated results.

How To Change The ‘page’ Key Query Param.

There are two ways to do this,
1. Pass the custom name in the paginate function.
2. Use the setPageName function on the paginated results.

Solution 1

Pass the custom name in the paginate function. The ‘paginate’ method in Laravel accepts three parameters.

  1. The number of records per page
  2. The fields to return
  3. The page URL key. (This is what we are interested in.)

In our example, these are the default values for the second and third parameters.

The second parameter is an array of the columns you would like to return in the response, the default is ‘*’ which means all fields. However, our interest lies in the third parameter ‘page’ where you can set the key name you want. We are going to call it ‘users_per_page’.

Now if we retrieve the results again, we should see the URL query string change from the default to ‘users_per_page’.

Solution 2

Use the setPageName function on the paginated results.

Results

Using either of the methods above should give you your expected results as below.

Pagination with custom query string key.

I closed out the data layer to put more focus on the pagination metadata.

In there, we can see all the page URLs having our custom key ‘users_per_page’ instead of the default ‘page’;

page=2’ is now ‘users_per_page=2’ .

Conclusion

This is a small change that can save you a lot of time if you ever need to load multiple paginated results in a single response. Read more about Laravel’s pagination here.

--

--