Laravel Caching: Cache::remember and Safe Invalidation
Caching is the quickest way to make a slow page fast, and the quickest way to show users stale data. The code to store a value is one line. The hard part is deciding when to throw it away. This guide covers the Laravel cache tools you will use most and a safe approach to invalidation.
What this article is, and is not
This is a how-to for current Laravel versions. I give no speed-up numbers, because they depend on what you cache and which driver you use. The sitemap on this very site uses the pattern described below: it is built once, cached for an hour, and cleared whenever a post, page or tool is saved or deleted.
Cache::remember
use Illuminate\Support\Facades\Cache;
$stats = Cache::remember('dashboard.stats', 600, function () {
return [
'posts' => Post::count(),
'comments' => Comment::count(),
];
});
If the key exists, Laravel returns it. If not, it runs the closure, stores the result for 600 seconds and returns it. Use Cache::rememberForever() when you will clear the key yourself.
Choose a cache driver
Set CACHE_STORE in .env. file and database work anywhere, including shared hosting. redis and memcached are faster and support cache tags, but need a server. array stores values only for the current request and is used in tests.
Invalidate when the data changes
Time-based expiry alone means users may see old data until the time runs out. For data that changes on a known event, delete the key when it happens:
// In AppServiceProvider::boot()
Post::saved(fn () => Cache::forget('dashboard.stats'));
Post::deleted(fn () => Cache::forget('dashboard.stats'));
Keep a short expiry as well as event-based clearing. If an event is ever missed, the cache still fixes itself.
Keys matter
- Include everything that changes the result in the key:
"posts.index.page.{$page}", not just "posts.index".
- Never cache data that is different for each user under a shared key, or one user can see another's data.
- Put keys in one place, such as a constant or helper, so you clear exactly what you stored.
Cache tags (Redis and Memcached only)
Cache::tags(['posts'])->remember("post.{$id}", 3600, fn () => Post::find($id));
Cache::tags(['posts'])->flush();
Tags let you clear a group at once. They are not supported by the file and database drivers, so on those you must forget keys one by one.
Avoid a stampede
When a popular key expires, many requests can try to rebuild it at the same moment. For expensive results, take a lock so only one does the work:
Cache::lock('rebuild-report', 30)->block(5, function () {
Cache::put('report', buildReport(), 600);
});
Test it
Cache::put('dashboard.stats', ['posts' => 0]);
Post::factory()->create();
$this->assertNull(Cache::get('dashboard.stats')); // cleared by the saved event
Common mistakes
- Caching before you know the page is slow. Measure first, then cache the slowest part.
- Caching user-specific data under a key shared by everyone.
- Using tags on the file or database driver and finding they do nothing useful.
- Running
config:cache and then changing .env without clearing it, which is a different cache with the same effect.
Summary
Use Cache::remember with a clear key, clear it on the events that change the data, keep a time limit as a safety net, and measure before and after so you know it helped.