Skip to main content
Tutorial Free

Laravel Pagination: Keep Query Parameters on Second Page

July 05, 2023
2 min read

One of the typical issues with pagination is if you have more filters with GET parameters on your page. How to keep them from disappearing when the user clicks to visit /?page=2?


The Problem: Explained

A typical list of pagination links is built from the Controller like this:

$users = User::paginate();

If your page URL is /users, then the Blade directive of {{ $users->links() }} forms the URLs like:

  • /users?page=2
  • /users?page=3
  • and so on

But what if your URL is /users?role=admin?

Pagination links will stay the same, meaning the second page will lose the role filter. What to do?


The Solution: Appends or Query String

You can do two things to keep the GET parameters on the following pages.

1. Keep all parameters: withQueryString()

Just chain one more method at the end:

$users = User::paginate()->withQueryString();

2. Keep Only Specific parameters: appends()

If you care only about certain parameters, specify them with their values:

$users = User::paginate()->appends([
'role' => $request->role,
'group' => $request->group,
]);

Then, the resulting links for all the other pages would be like:

  • /users?role=admin&group=1&page=2
  • /users?role=admin&group=1&page=3
  • and so on

You can read more about Laravel pagination in the official documentation.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.