Skip to content

Laravel Cache::flexible stale-while-revalidate caching

PHP Dasun Kalupahana 338 views

<?php

use Illuminate\Support\Facades\Cache;

// Fresh for 5 seconds, then served stale for up to 10 more seconds while it refreshes.
$stats = Cache::flexible('dashboard.stats', [5, 10], function () {
    return [
        'users'  => \App\Models\User::count(),
        'orders' => \App\Models\Order::count(),
    ];
});

Serves the cached value instantly, even after it goes stale, and refreshes it in the background after the response is sent. Use it for slow queries on busy pages so no visitor waits on a cache miss. Needs Laravel 11.23+.

Learn more on the blog

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.