Queue, Events and Broadcasting

Ali
2 min readJan 13, 2021

If you look into the .env file for your Laravel project, you may find default queue driver for Laravel is sync;

QUEUE_CONNECTION=sync

That’s Laravel’s way of saying don’t do anything and run on the main thread; and if you have a long running task on your thread like firing an email or call third party API; the response will come back to you only when email/API complete their execution. Of course, that’s not ideal and we use queues for that to put the long running tasks on their own threads in the background.

For starters you want to use database driver (although you can also use in-memory Redis DB which is pretty fast for large projects; for more check the Laravel docs), meaning it would use database tables for its queue management.

To get started set queue driver to database in you .env file.

QUEUE_CONNECTION=database

Then run a few console commands like so:

php artisan queue:table // creates job table migration
php artisan migrate // migrate your database
php artisan make:job SendInvoiceEmail // create new job

It will generate following class into your app/Jobs directory.

class SendInvoiceEmail implements ShouldQueue{  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;  // use Job’s constructor as an opportunity to send your payload to    the jobpublic function __construct($payload){  $this->payload = $payload;}//public function handle(){  // Email sending login goes here  // you can access $this->payload}

Then from your controller which would be main thread:


// now this will be queued on background thread
SendInvoiceEmail::dispatch($payload);

Pusher and Queues:

Anyone who have a little experience with Laravel know that it provides a nice way of implementing socket programming. But what you may not know is that Pusher uses events, and events in tern use queues (by default).

class SendInvoiceEmailSent implements ShouldBroadcast{use Dispatchable, InteractsWithSockets, SerializesModels;public function __construct($payload){$this-> payload = $payload;}public function broadcastOn(){return new PrivateChannel(‘temperature-reading.’.$this->attachedDeviceId);}

In your controller

SendInvoiceEmailSent::dispatch($payload);

As you can see ‘SendInvoiceEmailSent’ implements ShouldBroadcast, which means put this thing on the queue, which may or may not what you want. E.g sometimes you may want to trigger the broadcast immediately as soon the trigger is happened so it should reach Pusher servers immediately, so you may want to update the UI as soon as possible on frontend (just as an example). For that one can do that:

SendInvoiceEmailSent implements ShouldBroadcastNow (this will trigger the event using main thread and not the queue without any delay).

Happy Coding!!!

--

--