thebigk's avatar
Level 13

Pagination and parameters other than ?page=x

I'm currently following Jeff's Episode #16 of Building Forum: https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/16 and decided to play with pagination a bit more.

I was stuck at pagination where the user filters the thread by username. So I had pagination failing at:

https://forum.app/threads?by=JohnDoe&page=3

Pagination failed because the {{ $threads->links() }} refused to acknowledge the presence of ?by=JohnDoe in the URL and directly linked to forum.app/threads&page=3.

After reading old discussions on stackexchange, I decided to try:

{{ $threads->appends(Request::except('page'))->links() }}

...and voila, it works!

I've no clue why. Can someone tell me what exactly is happening at the 'appends(blah blah) part? I mean, I know it's passing in the request, but how is Laravel handling it?

...also, is that the right way of doing it?

PS: I really appreciate this community and the help fellow members offer. It's super useful and has helped me pace up my learning speed. Thank you, folks! You're awesome.

0 likes
3 replies
gator's avatar

"appends" literally appends the array that is passed in as parameter. So,

appends('by'=>'JohnDoe')

does what you need.

Now, the links() method already generates a "page" query string parameter. So, we need to exclude that when chaining to links(). Request::except('page') gives you an array of all the querystring parameters EXCEPT the page parameter.

i.e. when the url is

https://forum.app/threads?by=JohnDoe&page=3

Request::except('page') returns

['by'=>'JohnDoe']

which is what you want to append.

thebigk's avatar
Level 13

Thanks @gator . If I understand it correctly, appends(Request::all()) would put all the stuff currently in request to the URL. But then, how would it preserve the structure of the string? I mean the '?<parameter' part.

Also, is the code I mentioned in my first post is the right way to achieve pagination on threads with existing GET parameters?

Please or to participate in this conversation.