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

Kenshirou's avatar

Why 'popular' is not preserved on query string when I change pages

This question is from the 'Hands On: Community Contributions' series, episode 12: 'Sort By Popularity'. When I am at the route: links-sharing.test/community and I typed '?popular' at the end it shows me a list ordered by most popular at links-sharing.test/community?popular. But When I click on a page on the custom pagination it doesn't preserve the '?popular' in the query string when I move from one page to another. Any idea for this behavior?

On my view:

...
{{ $links->appends(request()->query())->links() }}

On my controller:

$links = (new CommunityLinksQuery)->get(request()->exists('popular'), $category);
...

On my query class:

    class CommunityLinksQuery 
    {
        public function get($sortByPopular, $category)
        {
            $orderBy = $sortByPopular ? 'vote_count' : 'updated_at';

            return CommunityLink::with('votes', 'user', 'category')
                ->forCategory($category)
                ->where('approved', 1)
                ->leftJoin('community_links_votes', 'community_links_votes.community_link_id', '=', 'community_links.id')
                ->selectRaw(
                    'community_links.*, count(community_links_votes.id) as vote_count'
                )
                ->groupBy('community_links.id')
                ->orderBy($orderBy, 'desc')
                ->paginate(3);
        }
    }
0 likes
4 replies
Snapey's avatar

try append in the query

...

                ->groupBy('community_links.id')
                ->orderBy($orderBy, 'desc')
                ->paginate(3)
                ->appends(['popular' => request('popular')]);
        }


bugsysha's avatar
{{ $links->appends(['popular' => 'true'])->links() }}
Kenshirou's avatar

Thank you for the answers. I found out that the problem isn't in the source code. It's the framework version I'm using. Since Laravel 5.8+ a parameter alone with no value is not preserved in the query string by using appends(request()->query()).

I fixed it by adding a 'Most Popular' link with route:

link-sharing.test/community?popular=true

and another 'Most Recent' link with route:

link-sharing.test/community?popular=false

Modifying the code in the controller to:


$links = (new CommunityLinksQuery)->get(request('popular') == "true", $category);

always sort the list by either vote_count (Most Popular) or updated_at (Most Recent) and the popular parameter is preserved from page to page.

jlrdw's avatar

All you had to do was retrieve it in the requests each time.

Please or to participate in this conversation.