Ewomazino Ukah
Ewomazino Ukah

Reputation: 2366

how to execute events asynchronously in laravel

Pls I'm still new to laravel and I have used events in laravel a couple of times but I'm curious and would like to know if it's possible to execute an event in laravel asynchronously. Like for instance in the code below:

    <?php

    namespace mazee\Http\Controllers;

   class maincontroller extends Controller
   {
    public  function index(){
       Event::fire(new newaccountcreated($user)) ;
      //do something

    }

Is it possible for the block of code in the event listener of the "newaccountcreated" event to be executed asynchronously after the event is fired ?

Upvotes: 6

Views: 16266

Answers (2)

user3107673
user3107673

Reputation: 443

Filip's answer covers it all. I will add a bit more to it. If you push an event it will goto the default queue. You can specify a queue name as well. Have the listener class implements ShouldQueue and just include the queue method in the listener class like below.

/**
 * Push a new job onto the queue.
**/
public function queue($queue, $job, $data)
{
    return $queue->pushOn('queue-name', $job, $data);
}

Upvotes: 1

Filip Koblański
Filip Koblański

Reputation: 9988

Yes of course this is possible. You should read about Laravel Queues. Every driver (only not sync driver) are async. The easiest to configure is the database driver, but you can also want to try RabbitMQ server , here is Laravel bundle for it.

You can also add to your EventListener: newaccountcreated trait Illuminate\Queue\InteractsWithQueue (you can read about him here) which will helps you to connect it with Laravel Queue.

Upvotes: 11

Related Questions