thebigk's avatar
Level 13

Caching results breaks pagination

I've Redis cache configured and it's awesome. The only problem I'm facing is that pagination fails when using the following code -

$articles = Cache::store('redis')->remember('articles', 1, function() {
            return Article::where('active', 1)->latest()->paginate(5);
        });

The pagination links are rendered using {{$articles->render()}}. The problem is if I click on page numbers, only the cached page loads.

Is there any way to fix this problem?

0 likes
1 reply
bobbybouwmann's avatar
Level 88

Yes, you need to cache per page. So instead you can do something like this

$page = request()->get('page');
$articles = Cache::store('redis')->remember('articles-' . $page, 1, function() {
    return Article::where('active', 1)->latest()->paginate(5);
});

So now you have a cache per paginated page ;)

Please or to participate in this conversation.