How to prioritize queues in Laravel 5.3 events

Ivan Kolodii
2 min readMar 17, 2017

There is no predefined interface for changing queue for event listeners in Laravel 5.3. By default, it is always taken from your config.

My solution:

Create an abstract class for your listeners:

namespace App\Listeners;/**
* Class BaseListener
*/
abstract class BaseListener
{
/**
* Detects if class has queue or delay parameter
* If has queue parameter than pushes to certain queue
*
*
@param $queue
*
@param $job
*
@param $data
*
@return mixed
*/
public final function queue($queue, $job, $data)
{
if (isset($this->queue, $this->delay)) {
return $queue->laterOn($this->queue, $this->delay, $job, $data);
}

if (isset($this->queue)) {
return $queue->pushOn($this->queue, $job, $data);
}

if (isset($this->delay)) {
return $queue->later($this->delay, $job, $data);
}

return $queue->push($job, $data);
}
}

One more abstract class for high priority listeners:

namespace App\Listeners;

/**
* Class HighPriorityListener
*
*
@package App\Listeners
*/
abstract class HighPriorityListener extends BaseListener
{
/**
* Queue name
*
*
@var string
*/
protected $queue = 'high';
}

Now you can extend your listeners. Example:

class SendEmail extends HighPriorityListener implements ShouldQueue
{

/**
* Handle the event.
*
*
@param NewMessageReceived $event
*
@return void
*/
public function handle(NewMessageReceived $event)
{
//
}
}

To run a queue worker:

php artisan queue:work — queue=high,default

Now, all jobs from the “high” queue will be executed first. And after that that all from the default

One small tip due to event broadcasting:

If you want to broadcast an event immediately use ShouldBroadcastNow interface instead of ShouldBroadcast. It will use a sync driver for this event. Example:

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Queue\SerializesModels;

/**
* Class NewMessageReceived
*
*
@package App\Events\Messages
*/
class NewMessageReceived extends Event implements ShouldBroadcastNow
{
// some logic
}

And if you use ShouldBroadcast instead it will push jobs into the queue. It is not convenient if there are a lot of jobs in the queue. You will have to wait until the job is executed.

Hope this information can help someone. I was trying to find some info about it, but couldn’t find a thing.

Do your lara-well =)

--

--