I'm currently caching posts using laravel's built in caching with redis. however i'm running into a problem when caching posts. i basically have a column called score in the posts table that gets updated whenever user upvotes/downvotes and the problem is that if a user upvotes or downvotes a cached post the score column doesn't update until 10 minutes pass (that's how many minutes until the cache changes using laravel's built in Cache::remember function. What's the best way to solve this? Here is a code example of what i mean
public function home(Request $request)
{
//Get posts that have high scores and in the last 7 days..
// $posts = Post::with('user')->orderBy('score','desc')->whereRaw('created_at >= now() - INTERVAL 7 DAY')->paginate(30);
$page = $request->has('page') ? $request->query('page') : 1;
//$posts = Post::with('user')->orderBy('score','desc')->paginate(50);
$posts = Cache::remember('posts' . $page, 10, function(){
return Post::with('user')->orderBy('score','desc')->paginate(1);
});
return view('posts.home', compact('posts','page'));
}
Everything works perfectly and the posts are cached the problem appears when the user upvotes/downvotes. the score column doesn't update
TL;DR - don't cache what's frequently updating (especially if you do sorting along with pagination). Re-query your database and use indices for performance.
However, if you still want to chase your approach...
score should be updated in the database, but you get socalled stale data from the cache. You may want to Cache::forget('posts' . $page); when you update the score (I recommend using events), so you're querying the most uptodate data, whenever the score was updated.