Clear old elements on Redis Cache with Laravel

Pablo Reyes
1 min readJan 29, 2022
Photo by Julius Yls on Unsplash

Some methods on Laravel cache, dont have a direct way to set a ttl, like incremet. Or you do just an put method without any ttl. Well, on large applications, will be a problem. A huge DB with old unused values.

Removing old items on Redis

php artisan cache:clear-old-items

Command code

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class CacheClearOldItemsCommand extends Command
{
protected $signature = 'cache:clear-old-items {max_days_ttl=10}';
protected $description = 'Remove old created elements on redis cache.';

public function handle(): void
{
$redis = Redis::connection();
$max_ttl = $this->argument('max_days_ttl') * 24 * 3600;

foreach($redis->keys('*') as $item_key) {
$idle_time = $redis->object('idletime', $item_key);
if ($idle_time < $max_ttl)
{
continue;
}
$redis->del($item_key);
// $redis->unlink($item_key); // Redis >= 4.0.0
$this->line(
str_pad($item_key, 40)
.' | '.str_pad(now()->subSeconds($idle_time)->diffForHumans(), 20)
.' | deleted.'
);
}
}
}

Disclaimer: this command works with phpredis as Laravel database driver.

--

--

Pablo Reyes

Desarrollador Web. Emprendedor compulsivo. Apasionado por el cine, los viajes y la fotografía. CEO de SaldoAr y Reyesoft. Trato de no dejar nada a medi