ctf0
ctf0

Reputation: 7587

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().

Upvotes: 3

Views: 4775

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153140

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.

Upvotes: 4

Related Questions