Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
Reference / Laravel

Cache::flexible()

Stale-While-Revalidate caching pattern introduced in Laravel 11. Serves stale cached values immediately while refreshing data in background.

Syntax
Cache::flexible(string $key, array $durations, Closure $callback): mixed

Parameters

NameTypeDescription
keystringCache key.
durationsarray[freshSeconds, staleSeconds] window.
callbackClosureFresh value calculation closure.

Examples

Non-blocking cache refresh
$stats = Cache::flexible('leaderboard:global', [300, 3600], function () {
    return DB::table('users')->orderByDesc('points')->limit(50)->get();
});
Prevents cache stampede / dog-piling on high-traffic endpoints.