Jonty Behr  •  17 Feb 2018

How to queue Laravel Events

The Laravel documentation goes into a lot of detail of how to work with queues, and that page does a great job (excuse the pun) of explaining how to run your jobs through a queue.

Events and Listeners

The other alternative to queued jobs, is to use the Events and Listeners approach. We typically prefer this method, as its slightly more flexible: not only can easily dispatch one event to multiple listeners, but it also servers as a single point of truth (the EventServiceProvider lists all the events and listeners).

One thing that is somewhat different (and perhaps not immediately obvious) is that you are not placing the Event onto a queue; instead, the Listener itself is queued. Although this may seem counter-intuitive to start off with, it actually makes perfect sense. Think of it this way - the Event is only a method to dispatch something to a Listener, and each Listener can decide how to deal with that Event.

In the scenario where we have multiple Listeners for a single Event, then you can of course treat each Listener differently - maybe one listener uses a high-priority queue and another listener uses a lower priority queue. Or, you could even have one of the listeners using the sync method, whilst another uses redis.

Each Listener can specify its own queue parameters

Listeners will automatically use the default connection specified in your config/queue.php file. However, this can be overridden on a per-listener basis - have a look at the docs for more information on this topic.

End of the Line

There is more than one way to send items to a queue in Laravel; either by using Queued Jobs or Queued Event Listeners. Each method has pro's and con's, but for most purposes we recommend using Events and Queued Listeners.

So, go forth and queue.