Serve Cached Data Instantly in Laravel Using Cache::flexible()
When caching data in Laravel, developers usually do:
$products = Cache::remember('homepage-products', 600, function () {
return Product::latest()->take(20)->get();
});
This works well until the cache expires.
👉 The first user after expiration must wait while Laravel rebuilds the cache.
The Better Solution: Cache::flexible()
Laravel provides a built-in stale-while-revalidate pattern:
use Illuminate\Support\Facades\Cache;
$products = Cache::flexible(
'homepage-products',
[60, 300],
function () {
return Product::latest()->take(20)->get();
}
);
What Do These Numbers Mean?
[60, 300]
- First 60 seconds → Fresh cache
- Next 300 seconds → Serve stale cache and refresh in background
This means users continue getting a response instantly.
Real Project Example
Homepage trending articles:
$articles = Cache::flexible(
'trending-articles',
[120, 600],
fn () => Article::trending()->take(10)->get()
);
Instead of making users wait:
- Existing cache is returned immediately
- Laravel refreshes data behind the scenes
Why This Is Useful
It helps you:
- Reduce cache stampedes
- Improve response times
- Avoid traffic spikes after cache expiry
- Keep pages fast under heavy load
Perfect For
Use Cache::flexible() when caching:
- Homepage widgets
- Trending articles
- Product listings
- Dashboard statistics
- Public API responses