Skip to content

Instantly share code, notes, and snippets.

@sailingdeveloper
Last active December 3, 2018 13:43
Show Gist options
  • Save sailingdeveloper/c8a76bcbb44252d545ecda60f805aabe to your computer and use it in GitHub Desktop.
Save sailingdeveloper/c8a76bcbb44252d545ecda60f805aabe to your computer and use it in GitHub Desktop.
Specifying a default queue for a Job
published: true

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 on Listener.

@flyingL123
Copy link

I don't think this works anymore. On Laravel 5.6 the $queue property is declared on the Queueable trait. That means you can't override the property in the job class.

@flyingL123
Copy link

But this seems to work in the constructor of the job class:

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $data)
    {
        $this->queue = 'export';
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment