Skip to content

Conversation

Zwartpet
Copy link
Contributor

Problem

As a developer I would like to be able to refresh a stale flexible cache when the applications returns a non successful response code.

Right now in the Cache::flexible it is deferred without the always parameter:

public function flexible($key, $ttl, $callback, $lock = null)
{
    ...

    defer($refresh, "illuminate:cache:flexible:{$key}");

    return $value;
}

Proposal

An extra optional parameter alwaysDefer with a default value of false to make it a non-breaking change.

public function flexible($key, $ttl, $callback, $lock = null, $alwaysDefer = false)
{
    ...

    defer($refresh, "illuminate:cache:flexible:{$key}", $alwaysDefer);

    return $value;
}

Use cases

Using flexible cache in the PreventRequestsDuringMaintenance middleware

The app is heavily dependent on an external API and put the app in downtime when the external API is in maintenance or has downtime.

class PreventRequestsDuringMaintenance extends Middleware
{
    public function handle($request, Closure $next)
    {
        $isDown = Cache::flexible($url, [120, 600], function () {
            $response = Http::get('https://api.external.com/healthcheck');

            return $response->json('status') !== 'ok';
        }, alwaysDefer: true);

        if ($isDown) {
            throw new HttpException(
                503,
                'Service Unavailable'
            );
        }

        return parent::handle($request, $next);
    }
}

Using flexible cache in validations

In addition to the example above you could rely on an external API for specific data validations

class LocationsRule implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $locations = Cache::flexible($url, [120, 600], function () {
            $response = Http::get('https://api.external.com/available-locations');

            return $response->json('data');
        }, alwaysDefer: true);

        if (! in_array($value, $locations)) {
            $fail('The :attribute is not longer available.');
        }
    }
}

@taylorotwell taylorotwell merged commit d46604a into laravel:12.x May 21, 2025
61 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants