Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MediaLounge's avatar

How to avoid clearing a specific cache?

I have a service provider where I make API calls to an external API, however I need to get an access token that's only valid for 24 hours. The way I'm doing it is something like this:

public function makeRequest() {
    $accessToken = cache()->remember('access_token', now()->addHours(23), function () {
        // Get access token from API and return it

        return "access_token";
    });

    // Make actual request using $accessToken
}

This works well however the API has another limitation where they only allow up to 5 access token requests per day. This means that if I clear Laravel's cache I'll be making another request specially on my dev server where I need to deploy frequently so I keep hitting this request limit.

I was wondering if there's a way to make Laravel clear all caches except this one? I'm using Redis so I was thinking about using a specific tag for this and tagging everything else with a common tag that I can tell Laravel to clear but that seems inefficient, also it won't help if I use third party packages that use the cache and don't implement this tag.

Thanks!

0 likes
3 replies
Snapey's avatar

instead, you could save the token in the database?

MediaLounge's avatar

@Snapey I could but having it on redis helps avoid an extra DB query and I'll be using this API quite frequently. I managed to solve it by using a separate cache store though!

MediaLounge's avatar
MediaLounge
OP
Best Answer
Level 1

If anyone's interested I managed to solve this by using a separate cache store for this value:

database.php

'persistent' => [
    // Same as 'cache' except using a different DB
     'database' => env('REDIS_PERSISTENT_DB', '2'),
],

cache.php

'redis_persistent' => [
    'driver' => 'redis',
    'connection' => 'persistent',
    'lock_connection' => 'default',
],

And when storing values in the cache I use this "redis_persistent" store like:

$accessToken = cache()
    ->store('redis_persistent')
    ->remember('access_token', now()->addHours(23), function () {
        // ...
    });

The cache:clear command only clears the "cache" store by default so anything stored in "redis_persistent" is kept.

2 likes

Please or to participate in this conversation.