Obydul's avatar

How to Get the Expiry Time of a Redis Cache

Hello artisans,

Is there any way to get the expiry time of a Redis cache?

$cache_name = "category_15";
$cache_value = cache()->get($cache_name);

// is there any way to find ttl/pttl value? I tested the below one. 
$cache_expire_time = Redis::ttl($cache_name); //  always returns '-2'.

Thank you.

0 likes
5 replies
senaranya's avatar
Level 10

You need to specify the Redis connection configured in config/cache.php. By default it is cache, so the following should work:

$cache_name = "category_15";
$cache_value = cache()->get($cache_name);

$cache_expire_time = Redis::connection('cache')->ttl(config('cache.prefix') . ':' . $cache_name); //  Returns the expiry time remaining
4 likes
Niush's avatar

Laravel Cache will prefix the key using the value provided in /config/cache.php.

So, when using Redis facade directly you will have to include the prefix manually. Something like this:

Redis::ttl(config('cache.prefix') . $cache_name);
// there is also pttl function.
// It may return -2 if the key doesn't exist, or -1 if the key has no expiration set.
1 like
Sinnbeck's avatar

@Obydul if it worked, please mark a best answer to set the thread as solved

Please or to participate in this conversation.