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 ?
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With