How to empty all queued jobs in a redis database for a given queue in Laravel versions previous to Laravel 8 ?
Sometime when your queue is filling in a dev environment you want to clean all queued jobs to go back to a fresh start.
Laravel doesn't provide an easy way for doing so before 8.x and Redis database aren't the most intuitive to do this task manually.
Laravel 8+ makes it easy with the following command :
php artisan queue:clear redis --queue=queue_name
where queue name is the name of the specific queue you want to clear. default queue is called default
For laravel < 8 I created this artisan command specific to redis:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Redis;
class QueueClear extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'queue:clear {--queue=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Clear all jobs on a given queue in the redis database';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$queueName = $this->option('queue') ? $this->option('queue') : 'default';
$queueSize = Queue::size($queueName);
$this->warn('Removing ' . $queueSize . ' jobs from the ' . $queueName . ' queue...');
Redis::connection()->del([
'queues:' . $queueName,
'queues:' . $queueName . ':notify',
'queues:' . $queueName . ':delayed',
'queues:' . $queueName . ':reserved'
]);
$this->info($queueSize . ' jobs removed from the ' . $queueName . ' queue...');
}
}
In the app/Console/Commands/Kernel.php
file add the folloowing command:
protected $commands = [
'App\Console\Commands\QueueClear'
];
Then, depending on your queue you can call it that way:
Default queue
php artisan queue:clear
Specific queue
php artisan queue:clear --queue=queue_name