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

nhayder's avatar
Level 13

How to cache a paginated query

i'm fetching data from DB like this


public static function getArticleComments($arc_id)

    {
    
        $comments = Comment::with('user')

                            ->where('article_id', '=' , $arc_id)
                            
                            ->orderBy('id', 'desc')

                    ->paginate(10);

        return $comments;
                
    }

so my question is how to cache this paginated query ???

any idea

0 likes
6 replies
Sinnbeck's avatar

Sure. Replace the key. But should work 😊

$comments = Cache::remember('myAwesomeComments', 200, function () use ($arc_id) {
    return Comment::with('user')

                            ->where('article_id', '=' , $arc_id)
                            
                            ->orderBy('id', 'desc')

                    ->paginate(10);
});

return $comments;
shez1983's avatar
shez1983
Best Answer
Level 23

@sinnbeck that will not work...

you need to add to the key page you are on so

Cache::get('myAwesomeComments' . $request->get('page', 1), function...

page is laravels default get param it uses for pagination

otherwise no matter what you do (ie go to next page - you will get same results

2 likes
rodrigo.pedra's avatar

I used this package to handle query caching: watson/rememberable

it creates the cached results key based on the query and its bindings so it will cache each paged result separately.

Read the package's readme for installation guidance, after installing and configuring your model to use that the usage in your case would be something like this:

public static function getArticleComments($arc_id)

    {
    
        $comments = Comment::with('user')

                            ->where('article_id', '=' , $arc_id)
                            
                            ->orderBy('id', 'desc')

                    ->remember(60) // 60 minutes = 1 hour

                    ->paginate(10);

        return $comments;
                
    }

Sinnbeck's avatar

@shez1983 true if you don't set the key like I mentioned

(untested)

$key = 'comments'. request()->get('page_id');
$comments = Cache::remember($key, 200, function () use ($arc_id) {
    return Comment::with('user')

                            ->where('article_id', '=' , $arc_id)
                            
                            ->orderBy('id', 'desc')

                    ->paginate(10);
});

return $comments;
1 like
Snapey's avatar

What are you expecting to happen when you cache the query? If you are hoping to avoid re-running the query on pages 2,3,4 etc then this will have no effect since they are different queries.

The cache will only have a hit for the same arc_id and the same page

by the way $arc_id also needs to be part of the cache key

Please or to participate in this conversation.