Skip to content

Caching Laravel Queries the Right Way: Cache::remember with Automatic Invalidation

M Mohamed Khalifa
How to cache your public site queries without serving stale content, using model observers to invalidate the cache automatically on every save.

Most Laravel sites query the same content on every request: services, projects, settings. Wrapping those queries in Cache::remember() is easy — the hard part is invalidation.

The versioned key pattern

Instead of forgetting dozens of individual keys, keep a single version number and prefix every cache key with it:

$version = Cache::rememberForever('site:version', fn () => 1);
return Cache::remember("site:v{$version}:services", now()->addDay(), fn () => Service::active()->get());

Then register one observer for all content models that bumps the version on saved and deleted. Every cached query refreshes instantly after any dashboard edit, and stale keys simply expire.

Why not Cache::flush()?

Flushing wipes sessions and other caches sharing the store. Version bumping is surgical, works on every cache driver, and costs one extra get per request.

Back to Blog Performance

Keep reading

Related Articles

Next deploy

Got a project in mind? Let's build it right.

Open a production channel. Architecture first. Delivery owned end to end.

visitor@khalifadev:~ ● ready

$ Contact::connect();

✓ channel open

info@khalifadev.com

$ Mail::send( 'next-system' );