Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Event::queue in laravel?

I've read a lot about Event::queue but I just cant get my head around it, so i have something like:

Event::listen('send_notification');

and in the controller I use

Event::fire('send_notification');

But because this takes sometime before sending the user to somewhere else, I instead want to use

Event::queue('send_notification');

To fire the event after the user has been redirected, but I don't know how.

(In the app/config/app.php i have the queue driver set to sync)

EDIT:

a small note about firing the event ,u can do all ur work just like normal ,and add all the Event::flush() as a filter ,then just call that filter through ->after() or afterFilter().

like image 837
ctf0 Avatar asked Dec 11 '25 18:12

ctf0


1 Answers

First, let me make something clear. Event::queue has nothing to do with the Queue facade and the query driver in the config. It won't enable you to fire the event after the request has happened.

But you can delay the firing of an event and therefore "prepare" it.

The usage is pretty basic. Obviously you need one or many Event::listen (well it works without them but makes no sense at all)

Event::listen('send_notification', function($text){
    // send notification
});

Now we queue the event:

Event::queue('send_notification', array('Hello World'));

And finally, fire it by calling flush

Event::flush('send_notification');

In your comment you asked about flushing multiple events at once. Unfortunately that's not really possible. You have to call flush() multiple times

Event::flush('send_notification');
Event::flush('foo');
Event::flush('bar');

If you have a lot of events to flush you might need to think about your architecture and if it's possible to combine some of those into one event with multiple listeners.

Flushing the Event after redirect

Event::queue can't be used to fire an event after the request lifecycle has ended. You have to use "real" queues for that.

like image 112
lukasgeiter Avatar answered Dec 13 '25 19:12

lukasgeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!