Events

Basic Usage

The Laravel event facilities provides a simple observer implementation, allowing you to subscribe and listen for events in your application. Event classes are typically stored in the app/Events directory, while their handlers are stored in app/Handlers/Events.

You can generate a new event class using the Artisan CLI tool:

  1. php artisan make:event PodcastWasPurchased

Subscribing To An Event

The EventServiceProvider included with your Laravel application provides a convenient place to register all event handlers. The listen property contains an array of all events (keys) and their handlers (values). Of course, you may add as many events to this array as your application requires. For example, let's add our PodcastWasPurchased event:

  1. /**
  2. * The event handler mappings for the application.
  3. *
  4. * @var array
  5. */
  6. protected $listen = [
  7. 'App\Events\PodcastWasPurchased' => [
  8. 'App\Handlers\Events\EmailPurchaseConfirmation',
  9. ],
  10. ];

To generate a handler for an event, use the handler:event Artisan CLI command:

  1. php artisan handler:event EmailPurchaseConfirmation --event=PodcastWasPurchased

Of course, manually running the make:event and handler:event commands each time you need a handler or event is cumbersome. Instead, simply add handlers and events to your EventServiceProvider and use the event:generate command. This command will generate any events or handlers that are listed in your EventServiceProvider:

  1. php artisan event:generate

Firing An Event

Now we are ready to fire our event using the Event facade:

  1. $response = Event::fire(new PodcastWasPurchased($podcast));

The fire method returns an array of responses that you can use to control what happens next in your application.

You may also use the event helper to fire an event:

  1. event(new PodcastWasPurchased($podcast));

Closure Listeners

You can even listen to events without creating a separate handler class at all. For example, in the boot method of your EventServiceProvider, you could do the following:

  1. Event::listen('App\Events\PodcastWasPurchased', function($event)
  2. {
  3. // Handle the event...
  4. });

Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so using by returning false from your handler:

  1. Event::listen('App\Events\PodcastWasPurchased', function($event)
  2. {
  3. // Handle the event...
  4. return false;
  5. });

Queued Event Handlers

Need to queue an event handler? It couldn't be any easier. When generating the handler, simply use the —queued flag:

  1. php artisan handler:event SendPurchaseConfirmation --event=PodcastWasPurchased --queued

This will generate a handler class that implements the Illuminate\Contracts\Queue\ShouldBeQueued interface. That's it! Now when this handler is called for an event, it will be queued automatically by the event dispatcher.

If no exceptions are thrown when the handler is executed by the queue, the queued job will be deleted automatically after it has processed. If you need to access the queued job's delete and release methods manually, you may do so. The Illuminate\Queue\InteractsWithQueue trait, which is included by default on queued handlers, gives you access to these methods:

  1. public function handle(PodcastWasPurchased $event)
  2. {
  3. if (true)
  4. {
  5. $this->release(30);
  6. }
  7. }

If you have an existing handler that you would like to convert to a queued handler, simply add the ShouldBeQueued interface to the class manually.

Event Subscribers

Defining An Event Subscriber

Event subscribers are classes that may subscribe to multiple events from within the class itself. Subscribers should define a subscribe method, which will be passed an event dispatcher instance:

  1. class UserEventHandler {
  2. /**
  3. * Handle user login events.
  4. */
  5. public function onUserLogin($event)
  6. {
  7. //
  8. }
  9. /**
  10. * Handle user logout events.
  11. */
  12. public function onUserLogout($event)
  13. {
  14. //
  15. }
  16. /**
  17. * Register the listeners for the subscriber.
  18. *
  19. * @param Illuminate\Events\Dispatcher $events
  20. * @return void
  21. */
  22. public function subscribe($events)
  23. {
  24. $events->listen('App\Events\UserLoggedIn', '[email protected]');
  25. $events->listen('App\Events\UserLoggedOut', '[email protected]');
  26. }
  27. }

Registering An Event Subscriber

Once the subscriber has been defined, it may be registered with the Event class.

  1. $subscriber = new UserEventHandler;
  2. Event::subscribe($subscriber);

You may also use the service container to resolve your subscriber. To do so, simply pass the name of your subscriber to the subscribe method:

  1. Event::subscribe('UserEventHandler');