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

oroalej's avatar

Caching a query result

Hi,

What is the best way to cache a query result if the page have a filter option? Do I get all the result and cache it then just manipulate the result from there?

Thank you in advance guys.

0 likes
1 reply
Sanctuary's avatar
Level 12

This would really depend on your queries and amount of rows you have, and how you're implementing the filter. Some filters only allow you to filter one thing at a time, but some allow you to filter multiple.

If your filter only allows one at a time, you could do something like this:

$minutes = 60 * 24 * 7;
$option = $request->option;
$cacheNamespace = isset($option) ? "some:results:{$option}" : "some:results";

return Cache::remember($cacheNamespace, $minutes, function() use($option) {
    if (is_null($option)) 
        return Model::all();
    }

    return Model::where($option, '=', 'value')->get();
});

If you take multiple options, you could still do something similar. This approach can be beneficial, but depending on your situation, caching all the results and filtering through there may be better.

Please or to participate in this conversation.