Reputation: 827
Is there way to get the time left for a key to expire? Currently, I'm using Laravel file cache driver.
Upvotes: 6
Views: 10553
Reputation: 14539
Based on Josh's answer, I came up with a macro:
In AppServiceProvider
's boot
method:
Cache::macro('getTTL', function (string $key): ?int {
$fs = new class extends FileStore {
public function __construct()
{
parent::__construct(App::get('files'), config('cache.stores.file.path'));
}
public function getTTL(string $key): ?int
{
return $this->getPayload($key)['time'] ?? null;
}
};
return $fs->getTTL($key);
});
Usage:
Cache::getTTL('key_that_exists') // 20900 (in seconds)
Cache::getTTL('key_that_does_not_exist') // null
Note: This was tested in Laravel 10.0, using PHP 8.1.
Gist: https://gist.github.com/Script47/a0e189eb5b3a352517ae5185510f9e17
Upvotes: 4
Reputation: 3288
There is not a built-in method, no.
The code for Store
, of which FileStore
inherits, has this logic for checking if a cache item has expired before opening its contents.
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Cache/FileStore.php#L50-L86
If you wanted to accomplish this, you would need to copy this logic.
Upvotes: 6