Laravel cache is the difference between an app that answers in 20 milliseconds and one that runs the same expensive query on every single request. Most Laravel apps start with one Cache::remember() call and never look further — and that works, right up until a popular key expires under load, a stale value refuses to die, or a deploy wipes the wrong Redis database. This guide covers the whole arc: picking a driver, the core API, the newer flexible() and memo() helpers, cache tags for surgical invalidation, atomic locks for stampede-proof rebuilds, and the failover driver for when Redis goes down. Everything here is verified against the official Laravel 13.x cache documentation and current 2026 guides, and every code sample is copy-paste ready. Last verified: 23 November 2026.
How the Laravel Cache Works
Laravel gives you one expressive API — the Cache facade — that works the same no matter which backend stores the data. You configure the default store in config/cache.php and pick it with the CACHE_STORE environment variable (on Laravel 10 and older the variable was CACHE_DRIVER). The backends Laravel ships with are:
| Driver | Where data lives | Cache tags | Best for |
|---|---|---|---|
file |
storage/framework/cache |
No | Local development, single small server |
database |
Your app database (default in Laravel 11+) | No | Small apps with no extra infrastructure |
redis |
Redis, in memory | Yes | Production — fast, plus tags and locks |
memcached |
Memcached, in memory | Yes | High-throughput plain key/value caching |
dynamodb |
AWS DynamoDB table | No | AWS-hosted apps |
storage |
Any filesystem disk (S3 included) | No | Using an existing disk as a key/value store |
array / null |
Memory / nowhere | No | Automated tests |
Two facts in that table matter more than the rest. First, the default driver in a fresh Laravel 11+ app is database — every cache read is a query against the very database the cache exists to protect. Second, cache tags only work on Redis and Memcached. If you build your invalidation strategy around tags while running the database driver, you will get a BadMethodCallException the first time a tagged call runs.
For production, Redis is the safe default. It is fast, it supports tags and atomic locks, and the same server already backs queues, sessions, and rate limiting. If your host offers Valkey instead of Redis, the same Laravel redis driver and phpredis client work against it with no code changes — Valkey is a protocol-compatible fork.
Setting Up Redis as Your Laravel Cache Store
Before using a Redis cache with Laravel, install the PhpRedis PHP extension via PECL or the predis/predis package via Composer. Laravel Sail and official Laravel platforms such as Forge and Laravel Cloud already have PhpRedis installed. Then point the cache at Redis and give it its own database:
# .env
CACHE_STORE=redis
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_CACHE_DB=1
CACHE_PREFIX=myapp_cache
Three details in that block save you from real incidents:
- Separate Redis database for the cache. Laravel’s Redis cache store implements
flush()as aFLUSHDBcall on the cache connection. If the cache shares database 0 with your queues and sessions,php artisan cache:clearcan wipe queued jobs and sessions along with the cache. Keep the cache on database 1 and everything else on 0. - Set
CACHE_PREFIXexplicitly when several apps or environments share one Redis instance, otherwise a staging deploy can read production keys. - Set an eviction policy before you need one. Redis has a memory ceiling; when it fills up with no policy, writes start failing. A policy like
allkeys-lruon the cache database keeps the cache self-cleaning.
Confirm the store is actually what you think it is with php artisan config:show cache.default. If you are using the database driver, create its table first:
php artisan make:cache-table
php artisan migrate
The Core API: get, put, remember
Almost everything you do with the Laravel cache goes through a handful of methods on the Cache facade. The TTL argument accepts seconds as an integer, a DateTime, or a DateInterval — 600 and now()->addMinutes(10) mean the same thing.
use Illuminate\Support\Facades\Cache;
// Retrieve, with a default when the key is missing
$value = Cache::get('key');
$value = Cache::get('key', 'default');
$value = Cache::get('key', fn () => DB::table('users')->get());
// Store for 10 minutes (or indefinitely if no TTL is given)
Cache::put('key', 'value', 600);
Cache::put('key', 'value', now()->addMinutes(10));
Cache::put('key', 'value');
// Store only if the key does not already exist (atomic)
Cache::add('key', 'value', 600);
// Store forever — you must remove it yourself with forget()
Cache::forever('key', 'value');
// Retrieve and delete in one step
$value = Cache::pull('key');
// Counters
Cache::add('visits', 0, now()->addHours(4));
Cache::increment('visits');
Cache::decrement('visits');
// Extend the lifetime of an existing item (false if it is gone)
Cache::touch('key', 3600);
// Remove one key, or everything
Cache::forget('key');
Cache::flush();
Two warnings about flush(). First, it does not respect your configured cache prefix — it removes all entries from the cache store, so never run it against a Redis instance shared with other applications. Second, on the Redis driver it flushes the whole cache database, which is exactly why the separate-database setup above matters.
Cache::remember() Is the Method You Will Use Most
remember() is the cache-aside pattern in one call: return the cached value if it exists, otherwise run the closure, store its result, and return it.
$stats = Cache::remember('dashboard:stats', now()->addMinutes(10), function () {
return [
'orders' => Order::whereMonth('created_at', now()->month)->count(),
'revenue' => Order::whereMonth('created_at', now()->month)->sum('total'),
'signups' => User::whereMonth('created_at', now()->month)->count(),
];
});
On every hit for the next ten minutes, those three aggregate queries never touch the database. The closure only runs on a miss. Two siblings are worth knowing:
Cache::rememberForever('key', $closure)— same idea, no expiry. Use it for data that only changes when you explicitly invalidate it, like a list of countries or a feature-flag snapshot.Cache::rememberWithWarmth('key', $seconds, $closure)— returns[$value, $warm], where$warmtells you whether the value came from the cache or was freshly computed. That is genuinely useful for logging and metrics: you can record a cache-hit ratio without a second cache read.
You can also use the global cache() helper instead of the facade — cache('key') reads, cache(['key' => 'value'], $seconds) writes, and cache()->remember(...) gives you the full API.
Cache::flexible(): Stale-While-Revalidate, Built In
The classic weakness of remember() is expiry: the moment a popular key expires, the next unlucky user waits for the full recomputation. For data where a slightly stale answer is fine, Laravel 13.x ships Cache::flexible(), a built-in stale-while-revalidate pattern:
$value = Cache::flexible('users', [5, 10], function () {
return DB::table('users')->get();
});
The array is [fresh seconds, stale seconds]. Within the fresh period the cache returns immediately. During the stale period the stale value is served to the user and a deferred function refreshes the cached value after the response is sent — so nobody ever waits for the rebuild. Only after the stale period ends does a request recompute synchronously. Use it for dashboards, leaderboards, and any read-heavy page where data a few seconds old is harmless.
Cache::memo(): Stop Hitting the Cache Twice in One Request
Laravel’s memo driver stores resolved values in memory for a single request or job execution, so repeated reads of the same key do not hit the cache store again:
// First call hits the cache store; later calls in this request are free
$value = Cache::memo()->get('key');
$value = Cache::memo()->get('key'); // memoized, no cache hit
// Decorate a specific store, e.g. Redis
$value = Cache::memo('redis')->get('key');
Writes through the memoized cache automatically forget the memoized value and delegate to the underlying store, so you cannot read your own stale write. Reach for memo() when the same setting, permission set, or config value is read in several places during one request — a common pattern in middleware, policies, and Blade components.
Cache Tags: Invalidate Groups, Not the Whole Cache
Deleting one key is easy. Deleting everything related to a user when their data changes is where tags come in. A tag groups keys so you can flush them together, and tags only work on Redis and Memcached:
use Illuminate\Support\Facades\Cache;
// Store with tags
Cache::tags(['products', "product:{$product->id}"])
->put("product:{$product->id}", $product, 3600);
// Flush everything for one product when it changes
Cache::tags("product:{$product->id}")->flush();
// Flush the whole products collection on a bulk import
Cache::tags('products')->flush();
Three rules that catch people out:
- A tagged value can only be read with its tags.
Cache::get('product:1')returnsnullfor a value stored with tags — the tags are part of the key. Always read with the same ordered list of tags you wrote with. - Flushing a list of tags is a union, not an intersection.
Cache::tags(['people', 'authors'])->flush()removes everything tagged withpeopleorauthors. - Tag granularity is a design decision. One tag per aggregate root (
product:{id}) plus one per collection (products) is a good default: flush the aggregate tag on any mutation, the collection tag only on create or delete. Tag too broadly and one edit rebuilds the whole cache; tag too narrowly and you miss stale entries.
Wire Invalidation to Your Model Events
Tags only help if something actually flushes them. The cleanest place is an Eloquent observer, so invalidation lives next to the write path and can never be forgotten by a controller:
namespace App\Observers;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
class ProductObserver
{
public function saved(Product $product): void
{
Cache::tags(["product:{$product->id}"])->flush();
}
public function deleted(Product $product): void
{
Cache::tags(["product:{$product->id}", 'products'])->flush();
}
}
Register the observer in AppServiceProvider or via the #[ObservedBy] attribute on the model. One caution from the Laravel community: avoid writing to the cache inside save() — a stale write can land after a concurrent reader has already stored fresh data. Invalidate on write; let the next read rebuild.
Atomic Locks: The Stampede-Proof Rebuild
Here is the failure mode remember() cannot fix. A hot key expires; two hundred concurrent requests all miss at once; two hundred copies of the expensive query hit the database together. The response-time graph grows a spike every ten minutes that looks like a scheduled job nobody can find. Laravel’s atomic locks solve it — only one process rebuilds, the rest wait or serve something stale:
use Illuminate\Support\Facades\Cache;
function getPopularProducts(): Collection
{
$key = 'products:popular';
$ttl = 300;
if ($cached = Cache::get($key)) {
return $cached;
}
$lock = Cache::lock("lock:{$key}", 10);
try {
if ($lock->get()) {
// Double-check after acquiring the lock
if ($cached = Cache::get($key)) {
return $cached;
}
$data = Product::popular()->get();
Cache::put($key, $data, $ttl);
return $data;
}
} finally {
optional($lock)->release();
}
// Could not get the lock: serve a short-lived stale value
return Cache::remember($key, 5, fn () => Product::popular()->get());
}
The double-check after acquiring the lock is critical. Without it, every request that waited rebuilds the cache sequentially after the first one finishes. The lock API also gives you block($seconds) to wait for a lock instead of failing immediately (it throws a LockTimeoutException if the wait expires), refresh() to extend a lock you own during a long job, restoreLock($name, $owner) to release a lock from another process using its owner token, and forceRelease() when you need to clear a stuck lock regardless of owner.
withoutOverlapping() and funnel() for Concurrency Limits
The same lock machinery powers two higher-level helpers. withoutOverlapping() runs a closure only if no other instance is running across your infrastructure — it waits up to 10 seconds by default and throws LockTimeoutException if it cannot acquire the lock:
Cache::withoutOverlapping('nightly-report', function () {
// Only one instance runs, even across servers
}, lockFor: 120, waitFor: 5);
If you want controlled parallelism instead of exclusivity, funnel() caps concurrent executions at a number you choose — handy for throttling calls to a rate-limited third-party API from jobs or scheduled tasks:
Cache::funnel('stripe-sync')
->limit(3)
->releaseAfter(60)
->block(10)
->then(function () {
// At most 3 of these run at once
}, function () {
// Could not get a slot within 10 seconds
});
Both helpers need a store that supports locks — Redis or Memcached, not the file or database driver. If you use funnel() on an unsupported store, Laravel throws a BadMethodCallException.
Cache Failover: When Redis Goes Down
A cache that takes your app down with it has failed at its one job. The failover driver tries stores in order and falls through to the next one when the primary fails:
// config/cache.php
'failover' => [
'driver' => 'failover',
'stores' => [
'redis',
'database',
],
],
# .env
CACHE_STORE=failover
When a store operation fails and failover activates, Laravel dispatches a CacheFailedOver event — listen for it and alert, because a silently degraded cache is a slow incident. Note the trade-off: the fallback store will not have the primary’s data, so expect a burst of cache misses (and database load) while you are on the fallback. That is still far better than 500 errors.
What php artisan cache:clear Actually Clears (and What It Does Not)
New Laravel developers reach for cache:clear for every stale-data problem, and it only solves one of them. There are four different caches in a Laravel app, and they have four different commands:
php artisan cache:clear # application cache (Cache facade data)
php artisan config:clear # cached config (config:cache output)
php artisan route:clear # cached routes
php artisan view:clear # compiled Blade views
If you changed a .env value and nothing happened, that is config:clear, not cache:clear. If a route change is not showing, that is route:clear. And if you deploy with php artisan optimize, remember it re-caches config, routes, and events — run it after the new code is in place, not before.
7 Laravel Cache Mistakes That Quietly Undo the Gains
- Caching with the database driver in production. Every cache read becomes a query against the database you were trying to protect. Switch to Redis before launch, not after the first slow page.
- Building tags on a driver that does not support them. File and database stores throw on
tags(). Decide the driver first, design invalidation second. - No TTL jitter. A deploy warms a thousand keys with a 3600-second TTL; an hour later they all expire in the same second. Add
random_int(0, 300)to spread the cliff across five minutes — about a tenth of the TTL is enough. - Caching the whole paginated result keyed only by page. Keys must include every input that changes the result — user, filters, sort, page — or one user sees another’s data. Build keys from all inputs:
"user:{$user->id}:orders:{$status}:page:{$page}". - Remembering forever without an invalidation plan.
rememberForever()is a promise to invalidate by hand. If no code path ever callsforget()or flushes the tag, the value is permanent — including the bug in it. - Sharing one Redis database for cache, queues, and sessions. One
cache:clearthen takes your queued jobs and user sessions with it. Give the cache its own database. - Skipping the double-check inside the lock. Acquiring the lock and rebuilding unconditionally means every waiting request rebuilds in turn. Check the cache again after you hold the lock.
Production Checklist
CACHE_STORE=rediswith a dedicated Redis database and an explicitCACHE_PREFIX.- Eviction policy set on the cache database (
allkeys-lruis a sane default). - Hot keys use
remember()with deliberate TTLs plus jitter; latency-sensitive reads useflexible(). - Invalidation wired to model observers with per-aggregate and per-collection tags.
- Stampede-prone keys rebuilt behind a lock with the double-check pattern.
- Failover store configured, with an alert on the
CacheFailedOverevent. - Deploy script runs
config:clear/route:clear/view:clearwhere needed — and never runscache:clearagainst a shared Redis database.
Further Reading & References
- Cache — Laravel 13.x Documentation — the authoritative reference for every method in this guide: remember, flexible, memo, tags, locks, funnel, and failover.
- Laravel Redis Cache Guide, 2026 Performance Playbook — Stackmivo — the configuration footguns: separate Redis database, phpredis vs predis, eviction policy, and the Valkey note.
- Use Redis as the Laravel Cache Store With Tags and Locking — ZeroExp — measured read latencies (0.29 ms database vs 0.088 ms Redis) and a runnable stampede experiment.
- How to Cache Expensive Queries in Laravel — Oatllo — TTL judgement calls, collision-proof key design, and model-change invalidation.
- Laravel Caching: Tags, Stampede Locks & Cache-Aside — Mohamed Said — tag granularity rules, the double-check pattern, and the cache-aside service class.
- Laravel Caching with Redis, Past the Basics — Sandeep Kumar — TTL jitter, why
block()is the piece people miss, and the real cost of tags. - Laravel Caching Explained: Complete Guide (2026) — Rami Dabdoub — a full walkthrough of drivers, expiration, and invalidation for comparison.
- How to Implement Caching in Laravel Using Different Caching Tools — Coder Legion — a practical step-by-step pass through drivers, remember, tags, and API-response caching.
Related on HowToShipIt: How to Speed Up Laravel Queries: 10 Fixes to Try Before You Upgrade Your Server, How to Run Laravel Queue Workers in Production with Supervisor, and Laravel Scheduler: The Complete Guide to Scheduled Tasks — the scheduler post covers withoutOverlapping() from the scheduling side.



