Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Devedge's avatar

Pagination issue with Spatie Laravel tags (not returning original query)

I'm looking for help with pagination when using Spatie Laravel-Tags, please.

Here's the setup…

I've coded up a really simple form which has multiple options for types of tags, so there's a select menu with options for types of post(for example, 'company news' and 'industry news') and then there's another for 'Author' etc (I'm trying to make it flexible so I can add more filters in the future if required).

<form action="/posts-search" method="get">

They're just standard selects with names of 'filter_term[0]' and 'filter_term[1]' so they create an array which I call '$tags' in the controller like this (it also has a category_id to search only in the current category):

$category->setRelation('posts', $category->posts()->withAllTags($tags, 'post')->paginate(12));

I've run a test and it returns the correct posts on the first 'results' page as well as the correct number of posts I'm expecting ('Showing 1 to 12 of 37 results' which is correct, so I know its working), however the post pagination doesn't work because it just shows '/posts-search?page=2' etc. It doesn't pick up the query from the form I'm sending.

If I check the URL the first time I run the search, I see the following:

/posts-search?_token=[TOKEN_IS_HERE]&filter_category=2&filter_term%5B0%5D=industry_news&filter_term%5B1%5D=bob_smith

When the results are being returned in the view, how can I get it to append the current search query to the paginated URLs so it returns the correct posts for the following page?

Many thanks.

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

It will remove your ?tags[]=foo :)

Add this to fix it

$category->setRelation('posts', $category->posts()->withAllTags($tags, 'post')
->paginate(12))
->withQueryString(); //Here
1 like
Devedge's avatar

Thanks once more @sinnbeck, although there was a typo in your code :). I think it needed to go immediately after ->paginate(12), not after ->paginate(12)) …

$category->setRelation('posts', $category->posts()->withAllTags($tags, 'post')
->paginate(12)
->withQueryString()
);

That did the trick. Thanks so much for your help!

Please or to participate in this conversation.