Events

Introduction

Laravel's events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don't worry if you don't see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.

Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

Registering Events & Listeners

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

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

Generating Events & Listeners

Of course, manually creating the files for each event and listener is cumbersome. Instead, add listeners and events to your EventServiceProvider and use the event:generate command. This command will generate any events or listeners that are listed in your EventServiceProvider. Events and listeners that already exist will be left untouched:

  1. php artisan event:generate

Manually Registering Events

Typically, events should be registered via the EventServiceProvider $listen array; however, you may also register Closure based events manually in the boot method of your EventServiceProvider:

  1. /**
  2. * Register any other events for your application.
  3. *
  4. * @return void
  5. */
  6. public function boot()
  7. {
  8. parent::boot();
  9. Event::listen('event.name', function ($foo, $bar) {
  10. //
  11. });
  12. }

Wildcard Event Listeners

You may even register listeners using the * as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the event name as their first argument, and the entire event data array as their second argument:

  1. Event::listen('event.*', function ($eventName, array $data) {
  2. //
  3. });

Event Discovery

{note} Event Discovery is available for Laravel 5.8.9 or later.

Instead of registering events and listeners manually in the $listen array of the EventServiceProvider, you can enable automatic event discovery. When event discovery is enabled, Laravel will automatically find and register your events and listeners by scanning your application's Listeners directory. In addition, any explicitly defined events listed in the EventServiceProvider will still be registered.

Laravel finds event listeners by scanning the listener classes using reflection. When Laravel finds any listener class method that begins with handle, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:

  1. use App\Events\PodcastProcessed;
  2. class SendPodcastProcessedNotification
  3. {
  4. /**
  5. * Handle the given event.
  6. *
  7. * @param \App\Events\PodcastProcessed
  8. * @return void
  9. */
  10. public function handle(PodcastProcessed $event)
  11. {
  12. //
  13. }
  14. }

Event discovery is disabled by default, but you can enable it by overriding the shouldDiscoverEvents method of your application's EventServiceProvider:

  1. /**
  2. * Determine if events and listeners should be automatically discovered.
  3. *
  4. * @return bool
  5. */
  6. public function shouldDiscoverEvents()
  7. {
  8. return true;
  9. }

By default, all listeners within your application's Listeners directory will be scanned. If you would like to define additional directories to scan, you may override the discoverEventsWithin method in your EventServiceProvider:

  1. /**
  2. * Get the listener directories that should be used to discover events.
  3. *
  4. * @return array
  5. */
  6. protected function discoverEventsWithin()
  7. {
  8. return [
  9. $this->app->path('Listeners'),
  10. ];
  11. }

In production, you likely do not want the framework to scan all of your listeners on every request. Therefore, during your deployment process, you should run the event:cache Artisan command to cache a manifest of all of your application's events and listeners. This manifest will be used by the framework to speed up the event registration process. The event:clear command may be used to destroy the cache.

{tip} The event:list command may be used to display a list of all events and listeners registered by your application.

Defining Events

An event class is a data container which holds the information related to the event. For example, let's assume our generated OrderShipped event receives an Eloquent ORM object:

  1. <?php
  2. namespace App\Events;
  3. use App\Order;
  4. use Illuminate\Queue\SerializesModels;
  5. class OrderShipped
  6. {
  7. use SerializesModels;
  8. public $order;
  9. /**
  10. * Create a new event instance.
  11. *
  12. * @param \App\Order $order
  13. * @return void
  14. */
  15. public function __construct(Order $order)
  16. {
  17. $this->order = $order;
  18. }
  19. }

As you can see, this event class contains no logic. It is a container for the Order instance that was purchased. The SerializesModels trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's serialize function.

Defining Listeners

Next, let's take a look at the listener for our example event. Event listeners receive the event instance in their handle method. The event:generate command will automatically import the proper event class and type-hint the event on the handle method. Within the handle method, you may perform any actions necessary to respond to the event:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderShipped;
  4. class SendShipmentNotification
  5. {
  6. /**
  7. * Create the event listener.
  8. *
  9. * @return void
  10. */
  11. public function __construct()
  12. {
  13. //
  14. }
  15. /**
  16. * Handle the event.
  17. *
  18. * @param \App\Events\OrderShipped $event
  19. * @return void
  20. */
  21. public function handle(OrderShipped $event)
  22. {
  23. // Access the order using $event->order...
  24. }
  25. }

{tip} Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel service container, so dependencies will be injected automatically.

Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.

Queued Event Listeners

Queueing listeners can be beneficial if your listener is going to perform a slow task such as sending an e-mail or making an HTTP request. Before getting started with queued listeners, make sure to configure your queue and start a queue listener on your server or local development environment.

To specify that a listener should be queued, add the ShouldQueue interface to the listener class. Listeners generated by the event:generate Artisan command already have this interface imported into the current namespace, so you can use it immediately:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderShipped;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. class SendShipmentNotification implements ShouldQueue
  6. {
  7. //
  8. }

That's it! Now, when this listener is called for an event, it will be automatically queued by the event dispatcher using Laravel's queue system. If no exceptions are thrown when the listener is executed by the queue, the queued job will automatically be deleted after it has finished processing.

Customizing The Queue Connection & Queue Name

If you would like to customize the queue connection, queue name, or queue delay time of an event listener, you may define the $connection, $queue, or $delay properties on your listener class:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderShipped;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. class SendShipmentNotification implements ShouldQueue
  6. {
  7. /**
  8. * The name of the connection the job should be sent to.
  9. *
  10. * @var string|null
  11. */
  12. public $connection = 'sqs';
  13. /**
  14. * The name of the queue the job should be sent to.
  15. *
  16. * @var string|null
  17. */
  18. public $queue = 'listeners';
  19. /**
  20. * The time (seconds) before the job should be processed.
  21. *
  22. * @var int
  23. */
  24. public $delay = 60;
  25. }

Conditionally Queueing Listeners

Sometimes, you may need to determine whether a listener should be queued based on some data that's only available at runtime. To accomplish this, a shouldQueue method may be added to a listener to determine whether the listener should be queued and executed synchronously:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderPlaced;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. class RewardGiftCard implements ShouldQueue
  6. {
  7. /**
  8. * Reward a gift card to the customer.
  9. *
  10. * @param \App\Events\OrderPlaced $event
  11. * @return void
  12. */
  13. public function handle(OrderPlaced $event)
  14. {
  15. //
  16. }
  17. /**
  18. * Determine whether the listener should be queued.
  19. *
  20. * @param \App\Events\OrderPlaced $event
  21. * @return bool
  22. */
  23. public function shouldQueue(OrderPlaced $event)
  24. {
  25. return $event->order->subtotal >= 5000;
  26. }
  27. }

Manually Accessing The Queue

If you need to manually access the listener's underlying queue job's delete and release methods, you may do so using the Illuminate\Queue\InteractsWithQueue trait. This trait is imported by default on generated listeners and provides access to these methods:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderShipped;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class SendShipmentNotification implements ShouldQueue
  7. {
  8. use InteractsWithQueue;
  9. /**
  10. * Handle the event.
  11. *
  12. * @param \App\Events\OrderShipped $event
  13. * @return void
  14. */
  15. public function handle(OrderShipped $event)
  16. {
  17. if (true) {
  18. $this->release(30);
  19. }
  20. }
  21. }

Handling Failed Jobs

Sometimes your queued event listeners may fail. If queued listener exceeds the maximum number of attempts as defined by your queue worker, the failed method will be called on your listener. The failed method receives the event instance and the exception that caused the failure:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\OrderShipped;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class SendShipmentNotification implements ShouldQueue
  7. {
  8. use InteractsWithQueue;
  9. /**
  10. * Handle the event.
  11. *
  12. * @param \App\Events\OrderShipped $event
  13. * @return void
  14. */
  15. public function handle(OrderShipped $event)
  16. {
  17. //
  18. }
  19. /**
  20. * Handle a job failure.
  21. *
  22. * @param \App\Events\OrderShipped $event
  23. * @param \Exception $exception
  24. * @return void
  25. */
  26. public function failed(OrderShipped $event, $exception)
  27. {
  28. //
  29. }
  30. }

Dispatching Events

To dispatch an event, you may pass an instance of the event to the event helper. The helper will dispatch the event to all of its registered listeners. Since the event helper is globally available, you may call it from anywhere in your application:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Order;
  4. use App\Events\OrderShipped;
  5. use App\Http\Controllers\Controller;
  6. class OrderController extends Controller
  7. {
  8. /**
  9. * Ship the given order.
  10. *
  11. * @param int $orderId
  12. * @return Response
  13. */
  14. public function ship($orderId)
  15. {
  16. $order = Order::findOrFail($orderId);
  17. // Order shipment logic...
  18. event(new OrderShipped($order));
  19. }
  20. }

{tip} When testing, it can be helpful to assert that certain events were dispatched without actually triggering their listeners. Laravel's built-in testing helpers makes it a cinch.

Event Subscribers

Writing Event Subscribers

Event subscribers are classes that may subscribe to multiple events from within the class itself, allowing you to define several event handlers within a single class. Subscribers should define a subscribe method, which will be passed an event dispatcher instance. You may call the listen method on the given dispatcher to register event listeners:

  1. <?php
  2. namespace App\Listeners;
  3. class UserEventSubscriber
  4. {
  5. /**
  6. * Handle user login events.
  7. */
  8. public function handleUserLogin($event) {}
  9. /**
  10. * Handle user logout events.
  11. */
  12. public function handleUserLogout($event) {}
  13. /**
  14. * Register the listeners for the subscriber.
  15. *
  16. * @param \Illuminate\Events\Dispatcher $events
  17. */
  18. public function subscribe($events)
  19. {
  20. $events->listen(
  21. 'Illuminate\Auth\Events\Login',
  22. 'App\Listeners\[email protected]'
  23. );
  24. $events->listen(
  25. 'Illuminate\Auth\Events\Logout',
  26. 'App\Listeners\[email protected]'
  27. );
  28. }
  29. }

Registering Event Subscribers

After writing the subscriber, you are ready to register it with the event dispatcher. You may register subscribers using the $subscribe property on the EventServiceProvider. For example, let's add the UserEventSubscriber to the list:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
  4. class EventServiceProvider extends ServiceProvider
  5. {
  6. /**
  7. * The event listener mappings for the application.
  8. *
  9. * @var array
  10. */
  11. protected $listen = [
  12. //
  13. ];
  14. /**
  15. * The subscriber classes to register.
  16. *
  17. * @var array
  18. */
  19. protected $subscribe = [
  20. 'App\Listeners\UserEventSubscriber',
  21. ];
  22. }