Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Caching with time filters

Given I am caching a query in laravel:

return Cache::remember('posts.all', 20, function(){
         return Post::all();
});

All fine.

My question is what if I want to apply filtering on the posts example get posts for last week

Post::whereBetween('created_at', [$from, $to])->get();

What if user selects a different date from the time picker example last month how that will work with caching ?

like image 440
PrStandup Avatar asked Jan 31 '26 04:01

PrStandup


1 Answers

If you'll do that, the same cached result will be given to all users. If you want to cache user specific data, you need to add user ID to the key:

Cache::remember('posts.all.' . auth()->id(), 20, function() use($from, $to) {
     return Post::whereBetween('created_at', [$from, $to])->get();
});

Then to get the data:

cache('posts.all.' . auth()->id())

Update

To make Laravel refresh the cached query result, you also need to cache from and to dates and check these.

if (cache('from' . auth().id()) !== $from || cache('to' . auth().id()) !== $to) {
    Cache::forget('posts.all.' . auth().id());
} 
like image 200
Alexey Mezenin Avatar answered Feb 03 '26 06:02

Alexey Mezenin