This package provides a polyfill for the Cache::flexible() method, which was introduced in Laravel 11. It brings the stale while revalidating cache pattern to Laravel 10.
When using Cache::remember, some users may experience slow response times if the cached value has expired. The flexible method allows stale data to be served while the cached value is recalculated in the background after the response is sent, preventing slow response times for your users.
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
You can install the package via composer:
composer require spatie/laravel-flexible-cache-polyfillUsing the Cache::flexible() facade:
$value = Cache::flexible('users', [5, 10], function () {
return DB::table('users')->get();
});The first value (5) is the number of seconds the cache is considered "fresh". The second value (10) defines how long it can be served as stale data before recalculation is necessary.
- 0-5 seconds: Returns cached value immediately
- 5-10 seconds: Returns stale value, refreshes in background after response is sent
- After 10 seconds: Cache expired, recalculates immediately
Support for all stores is available:
$value = Cache::store('redis-2')->flexible(...);composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.
