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

vinay8vee's avatar

Can we cache query run on pagination to count the results?

Can we cache query run on pagination to count the results. How can we do that? any plugins?

I don't want any query builder approach as it could impact all the models or queries in my existing system.

0 likes
6 replies
JabatoForever's avatar

Hi @vinay8vee ,For what i understand u want to cache the results of a pagination in order to do this you could try this approach.

$page = $request->get('page');
$per_page = $request->get('per_page');
$articles = cache()->remember("articles-$page-$per_page", '60*60*24',  
function() use ($page,$per_page){
        Article::query()->paginate($page,'','',$per_page);
});
vinay8vee's avatar

@JabatoForever Thanks to reply. My Problem is i have an existing api which have UserResource utilise to prepare the response payload which contains the pagination results.

and the query contains paginate method to fetch results and paginate result both.

so as you understand i want to avoid count(*) query as my query is quite complex and load is very high. ( on direct execution of query in phpmyadmin itself took some 3 seconds to fetch the result.

I want to cache the result of this query as per hourly basis.

as per my understanding the approach you have shared would contain that paginate query & normal result as well right?

jlrdw's avatar

@vinay8vee okay, makes sense.

I suggest cache the query, but with pagination being fast anyway, do you really need to cache that part. Admins should have direct access anyway.

vinay8vee's avatar

@jlrdw at first load we have display. currently business don't want to change functionality there.

Please or to participate in this conversation.