At my job, like a lot of Laravel projects, we have a project that has to run background tasks. The smartest things to do, is to execute these tasks in jobs. Some tasks have to be run quickly, like sending a welcome email, but other processes that might take minutes, don't have such a high priority. For these jobs, it's nice that Laravel offers multiple queues to put these lower priority jobs in.
However, when you dispatch these jobs in multiple places throughout your project, it's a little tedious to specify the queue every time:
dispatch((new Export)->onQueue('export'));
So I tried to find a way that allows me to specify a default queue for a job. I expected to find a method on the Job
class that I could overwrite, but it didn't exist. I then took a look at the onQueue
method to find out what exactly it does, and it's quite simple:
public function onQueue($queue)
{
$this->queue = $queue;
return $this;
}
All you have to do in order to set a default queue for a Job, is setting the property on the class, like so:
class Export extends Job implements ShouldQueue
{
public $queue = 'export';
}
Note: This works on all queuable classes, so apart from
Job
, this also works onListener
.
But this seems to work in the constructor of the job class: