Events
- Introduction
- Registering Events & Listeners
- Defining Events
- Defining Listeners
- Queued Event Listeners
- Dispatching Events
- Event Subscribers
Introduction
Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within 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 as 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 App\Events\OrderShipped
event which a listener can receive and use to dispatch a Slack notification.
Registering Events & Listeners
The App\Providers\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 an OrderShipped
event:
1use App\Events\OrderShipped;2use App\Listeners\SendShipmentNotification;34/**5 * The event listener mappings for the application.6 *7 * @var array8 */9protected $listen = [10 OrderShipped::class => [11 SendShipmentNotification::class,12 ],13];
1use App\Events\OrderShipped;2use App\Listeners\SendShipmentNotification;34/**5 * The event listener mappings for the application.6 *7 * @var array8 */9protected $listen = [10 OrderShipped::class => [11 SendShipmentNotification::class,12 ],13];
The event:list
command may be used to display a list of all events and listeners registered by your application.
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
Artisan command. This command will generate any events or listeners that are listed in your EventServiceProvider
that do not already exist:
1php artisan event:generate
1php artisan event:generate
Alternatively, you may use the make:event
and make:listener
Artisan commands to generate individual events and listeners:
1php artisan make:event PodcastProcessed23php artisan make:listener SendPodcastNotification --event=PodcastProcessed
1php artisan make:event PodcastProcessed23php artisan make:listener SendPodcastNotification --event=PodcastProcessed
Manually Registering Events
Typically, events should be registered via the EventServiceProvider
$listen
array; however, you may also register class or closure based event listeners manually in the boot
method of your EventServiceProvider
:
1use App\Events\PodcastProcessed;2use App\Listeners\SendPodcastNotification;3use Illuminate\Support\Facades\Event;45/**6 * Register any other events for your application.7 *8 * @return void9 */10public function boot()11{12 Event::listen(13 PodcastProcessed::class,14 [SendPodcastNotification::class, 'handle']15 );1617 Event::listen(function (PodcastProcessed $event) {18 //19 });20}
1use App\Events\PodcastProcessed;2use App\Listeners\SendPodcastNotification;3use Illuminate\Support\Facades\Event;45/**6 * Register any other events for your application.7 *8 * @return void9 */10public function boot()11{12 Event::listen(13 PodcastProcessed::class,14 [SendPodcastNotification::class, 'handle']15 );1617 Event::listen(function (PodcastProcessed $event) {18 //19 });20}
Queueable Anonymous Event Listeners
When registering closure based event listeners manually, you may wrap the listener closure within the Illuminate\Events\queueable
function to instruct Laravel to execute the listener using the queue:
1use App\Events\PodcastProcessed;2use function Illuminate\Events\queueable;3use Illuminate\Support\Facades\Event;45/**6 * Register any other events for your application.7 *8 * @return void9 */10public function boot()11{12 Event::listen(queueable(function (PodcastProcessed $event) {13 //14 }));15}
1use App\Events\PodcastProcessed;2use function Illuminate\Events\queueable;3use Illuminate\Support\Facades\Event;45/**6 * Register any other events for your application.7 *8 * @return void9 */10public function boot()11{12 Event::listen(queueable(function (PodcastProcessed $event) {13 //14 }));15}
Like queued jobs, you may use the onConnection
, onQueue
, and delay
methods to customize the execution of the queued listener:
1Event::listen(queueable(function (PodcastProcessed $event) {2 //3})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10)));
1Event::listen(queueable(function (PodcastProcessed $event) {2 //3})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10)));
If you would like to handle anonymous queued listener failures, you may provide a closure to the catch
method while defining the queueable
listener. This closure will receive the event instance and the Throwable
instance that caused the listener's failure:
1use App\Events\PodcastProcessed;2use function Illuminate\Events\queueable;3use Illuminate\Support\Facades\Event;4use Throwable;56Event::listen(queueable(function (PodcastProcessed $event) {7 //8})->catch(function (PodcastProcessed $event, Throwable $e) {9 // The queued listener failed...10}));
1use App\Events\PodcastProcessed;2use function Illuminate\Events\queueable;3use Illuminate\Support\Facades\Event;4use Throwable;56Event::listen(queueable(function (PodcastProcessed $event) {7 //8})->catch(function (PodcastProcessed $event, Throwable $e) {9 // The queued listener failed...10}));
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:
1Event::listen('event.*', function ($eventName, array $data) {2 //3});
1Event::listen('event.*', function ($eventName, array $data) {2 //3});
Event Discovery
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 PHP's reflection services. When Laravel finds any listener class method that begins with handle
or __invoke
, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:
1use App\Events\PodcastProcessed;23class SendPodcastNotification4{5 /**6 * Handle the given event.7 *8 * @param \App\Events\PodcastProcessed $event9 * @return void10 */11 public function handle(PodcastProcessed $event)12 {13 //14 }15}
1use App\Events\PodcastProcessed;23class SendPodcastNotification4{5 /**6 * Handle the given event.7 *8 * @param \App\Events\PodcastProcessed $event9 * @return void10 */11 public function handle(PodcastProcessed $event)12 {13 //14 }15}
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 bool5 */6public function shouldDiscoverEvents()7{8 return true;9}
1/**2 * Determine if events and listeners should be automatically discovered.3 *4 * @return bool5 */6public function shouldDiscoverEvents()7{8 return true;9}
By default, all listeners within your application's app/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 array5 */6protected function discoverEventsWithin()7{8 return [9 $this->app->path('Listeners'),10 ];11}
1/**2 * Get the listener directories that should be used to discover events.3 *4 * @return array5 */6protected function discoverEventsWithin()7{8 return [9 $this->app->path('Listeners'),10 ];11}
Event Discovery In Production
In production, it is not efficient for 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.
Defining Events
An event class is essentially a data container which holds the information related to the event. For example, let's assume an App\Events\OrderShipped
event receives an Eloquent ORM object:
1<?php23namespace App\Events;45use App\Models\Order;6use Illuminate\Broadcasting\InteractsWithSockets;7use Illuminate\Foundation\Events\Dispatchable;8use Illuminate\Queue\SerializesModels;910class OrderShipped11{12 use Dispatchable, InteractsWithSockets, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 public $order;2021 /**22 * Create a new event instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }31}
1<?php23namespace App\Events;45use App\Models\Order;6use Illuminate\Broadcasting\InteractsWithSockets;7use Illuminate\Foundation\Events\Dispatchable;8use Illuminate\Queue\SerializesModels;910class OrderShipped11{12 use Dispatchable, InteractsWithSockets, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 public $order;2021 /**22 * Create a new event instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }31}
As you can see, this event class contains no logic. It is a container for the App\Models\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, such as when utilizing queued listeners.
Defining Listeners
Next, let's take a look at the listener for our example event. Event listeners receive event instances in their handle
method. The event:generate
and make:listener
Artisan commands 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<?php23namespace App\Listeners;45use App\Events\OrderShipped;67class SendShipmentNotification8{9 /**10 * Create the event listener.11 *12 * @return void13 */14 public function __construct()15 {16 //17 }1819 /**20 * Handle the event.21 *22 * @param \App\Events\OrderShipped $event23 * @return void24 */25 public function handle(OrderShipped $event)26 {27 // Access the order using $event->order...28 }29}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;67class SendShipmentNotification8{9 /**10 * Create the event listener.11 *12 * @return void13 */14 public function __construct()15 {16 //17 }1819 /**20 * Handle the event.21 *22 * @param \App\Events\OrderShipped $event23 * @return void24 */25 public function handle(OrderShipped $event)26 {27 // Access the order using $event->order...28 }29}
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 email or making an HTTP request. Before using queued listeners, make sure to configure your queue and start a queue worker 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
and make:listener
Artisan commands already have this interface imported into the current namespace so you can use it immediately:
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;78class SendShipmentNotification implements ShouldQueue9{10 //11}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;78class SendShipmentNotification implements ShouldQueue9{10 //11}
That's it! Now, when an event handled by this listener is dispatched, the listener will automatically be 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<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;78class SendShipmentNotification implements ShouldQueue9{10 /**11 * The name of the connection the job should be sent to.12 *13 * @var string|null14 */15 public $connection = 'sqs';1617 /**18 * The name of the queue the job should be sent to.19 *20 * @var string|null21 */22 public $queue = 'listeners';2324 /**25 * The time (seconds) before the job should be processed.26 *27 * @var int28 */29 public $delay = 60;30}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;78class SendShipmentNotification implements ShouldQueue9{10 /**11 * The name of the connection the job should be sent to.12 *13 * @var string|null14 */15 public $connection = 'sqs';1617 /**18 * The name of the queue the job should be sent to.19 *20 * @var string|null21 */22 public $queue = 'listeners';2324 /**25 * The time (seconds) before the job should be processed.26 *27 * @var int28 */29 public $delay = 60;30}
If you would like to define the listener's queue connection or queue name at runtime, you may define viaConnection
or viaQueue
methods on the listener:
1/**2 * Get the name of the listener's queue connection.3 *4 * @return string5 */6public function viaConnection()7{8 return 'sqs';9}1011/**12 * Get the name of the listener's queue.13 *14 * @return string15 */16public function viaQueue()17{18 return 'listeners';19}
1/**2 * Get the name of the listener's queue connection.3 *4 * @return string5 */6public function viaConnection()7{8 return 'sqs';9}1011/**12 * Get the name of the listener's queue.13 *14 * @return string15 */16public function viaQueue()17{18 return 'listeners';19}
Conditionally Queueing Listeners
Sometimes, you may need to determine whether a listener should be queued based on some data that are only available at runtime. To accomplish this, a shouldQueue
method may be added to a listener to determine whether the listener should be queued. If the shouldQueue
method returns false
, the listener will not be executed:
1<?php23namespace App\Listeners;45use App\Events\OrderCreated;6use Illuminate\Contracts\Queue\ShouldQueue;78class RewardGiftCard implements ShouldQueue9{10 /**11 * Reward a gift card to the customer.12 *13 * @param \App\Events\OrderCreated $event14 * @return void15 */16 public function handle(OrderCreated $event)17 {18 //19 }2021 /**22 * Determine whether the listener should be queued.23 *24 * @param \App\Events\OrderCreated $event25 * @return bool26 */27 public function shouldQueue(OrderCreated $event)28 {29 return $event->order->subtotal >= 5000;30 }31}
1<?php23namespace App\Listeners;45use App\Events\OrderCreated;6use Illuminate\Contracts\Queue\ShouldQueue;78class RewardGiftCard implements ShouldQueue9{10 /**11 * Reward a gift card to the customer.12 *13 * @param \App\Events\OrderCreated $event14 * @return void15 */16 public function handle(OrderCreated $event)17 {18 //19 }2021 /**22 * Determine whether the listener should be queued.23 *24 * @param \App\Events\OrderCreated $event25 * @return bool26 */27 public function shouldQueue(OrderCreated $event)28 {29 return $event->order->subtotal >= 5000;30 }31}
Manually Interacting With 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<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * Handle the event.15 *16 * @param \App\Events\OrderShipped $event17 * @return void18 */19 public function handle(OrderShipped $event)20 {21 if (true) {22 $this->release(30);23 }24 }25}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * Handle the event.15 *16 * @param \App\Events\OrderShipped $event17 * @return void18 */19 public function handle(OrderShipped $event)20 {21 if (true) {22 $this->release(30);23 }24 }25}
Queued Event Listeners & Database Transactions
When queued listeners are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your listener depends on these models, unexpected errors can occur when the job that dispatches the queued listener is processed.
If your queue connection's after_commit
configuration option is set to false
, you may still indicate that a particular queued listener should be dispatched after all open database transactions have been committed by defining an $afterCommit
property on the listener class:
1<?php23namespace App\Listeners;45use Illuminate\Contracts\Queue\ShouldQueue;6use Illuminate\Queue\InteractsWithQueue;78class SendShipmentNotification implements ShouldQueue9{10 use InteractsWithQueue;1112 public $afterCommit = true;13}
1<?php23namespace App\Listeners;45use Illuminate\Contracts\Queue\ShouldQueue;6use Illuminate\Queue\InteractsWithQueue;78class SendShipmentNotification implements ShouldQueue9{10 use InteractsWithQueue;1112 public $afterCommit = true;13}
To learn more about working around these issues, please review the documentation regarding queued jobs and database transactions.
Handling Failed Jobs
Sometimes your queued event listeners may fail. If the 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 Throwable
that caused the failure:
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * Handle the event.15 *16 * @param \App\Events\OrderShipped $event17 * @return void18 */19 public function handle(OrderShipped $event)20 {21 //22 }2324 /**25 * Handle a job failure.26 *27 * @param \App\Events\OrderShipped $event28 * @param \Throwable $exception29 * @return void30 */31 public function failed(OrderShipped $event, $exception)32 {33 //34 }35}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * Handle the event.15 *16 * @param \App\Events\OrderShipped $event17 * @return void18 */19 public function handle(OrderShipped $event)20 {21 //22 }2324 /**25 * Handle a job failure.26 *27 * @param \App\Events\OrderShipped $event28 * @param \Throwable $exception29 * @return void30 */31 public function failed(OrderShipped $event, $exception)32 {33 //34 }35}
Specifying Queued Listener Maximum Attempts
If one of your queued listeners is encountering an error, you likely do not want it to keep retrying indefinitely. Therefore, Laravel provides various ways to specify how many times or for how long a listener may be attempted.
You may define a $tries
property on your listener class to specify how many times the listener may be attempted before it is considered to have failed:
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * The number of times the queued listener may be attempted.15 *16 * @var int17 */18 public $tries = 5;19}
1<?php23namespace App\Listeners;45use App\Events\OrderShipped;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Queue\InteractsWithQueue;89class SendShipmentNotification implements ShouldQueue10{11 use InteractsWithQueue;1213 /**14 * The number of times the queued listener may be attempted.15 *16 * @var int17 */18 public $tries = 5;19}
As an alternative to defining how many times a listener may be attempted before it fails, you may define a time at which the listener should no longer be attempted. This allows a listener to be attempted any number of times within a given time frame. To define the time at which a listener should no longer be attempted, add a retryUntil
method to your listener class. This method should return a DateTime
instance:
1/**2 * Determine the time at which the listener should timeout.3 *4 * @return \DateTime5 */6public function retryUntil()7{8 return now()->addMinutes(5);9}
1/**2 * Determine the time at which the listener should timeout.3 *4 * @return \DateTime5 */6public function retryUntil()7{8 return now()->addMinutes(5);9}
Dispatching Events
To dispatch an event, you may call the static dispatch
method on the event. This method is made available on the event by the Illuminate\Foundation\Events\Dispatchable
trait. Any arguments passed to the dispatch
method will be passed to the event's constructor:
1<?php23namespace App\Http\Controllers;45use App\Events\OrderShipped;6use App\Http\Controllers\Controller;7use App\Models\Order;8use Illuminate\Http\Request;910class OrderShipmentController extends Controller11{12 /**13 * Ship the given order.14 *15 * @param \Illuminate\Http\Request $request16 * @return \Illuminate\Http\Response17 */18 public function store(Request $request)19 {20 $order = Order::findOrFail($request->order_id);2122 // Order shipment logic...2324 OrderShipped::dispatch($order);25 }26}
1<?php23namespace App\Http\Controllers;45use App\Events\OrderShipped;6use App\Http\Controllers\Controller;7use App\Models\Order;8use Illuminate\Http\Request;910class OrderShipmentController extends Controller11{12 /**13 * Ship the given order.14 *15 * @param \Illuminate\Http\Request $request16 * @return \Illuminate\Http\Response17 */18 public function store(Request $request)19 {20 $order = Order::findOrFail($request->order_id);2122 // Order shipment logic...2324 OrderShipped::dispatch($order);25 }26}
If you would like to conditionally dispatch an event, you may use the dispatchIf
and dispatchUnless
methods:
1OrderShipped::dispatchIf($condition, $order);23OrderShipped::dispatchUnless($condition, $order);
1OrderShipped::dispatchIf($condition, $order);23OrderShipped::dispatchUnless($condition, $order);
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 subscriber 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<?php23namespace App\Listeners;45use Illuminate\Auth\Events\Login;6use Illuminate\Auth\Events\Logout;78class UserEventSubscriber9{10 /**11 * Handle user login events.12 */13 public function handleUserLogin($event) {}1415 /**16 * Handle user logout events.17 */18 public function handleUserLogout($event) {}1920 /**21 * Register the listeners for the subscriber.22 *23 * @param \Illuminate\Events\Dispatcher $events24 * @return void25 */26 public function subscribe($events)27 {28 $events->listen(29 Login::class,30 [UserEventSubscriber::class, 'handleUserLogin']31 );3233 $events->listen(34 Logout::class,35 [UserEventSubscriber::class, 'handleUserLogout']36 );37 }38}
1<?php23namespace App\Listeners;45use Illuminate\Auth\Events\Login;6use Illuminate\Auth\Events\Logout;78class UserEventSubscriber9{10 /**11 * Handle user login events.12 */13 public function handleUserLogin($event) {}1415 /**16 * Handle user logout events.17 */18 public function handleUserLogout($event) {}1920 /**21 * Register the listeners for the subscriber.22 *23 * @param \Illuminate\Events\Dispatcher $events24 * @return void25 */26 public function subscribe($events)27 {28 $events->listen(29 Login::class,30 [UserEventSubscriber::class, 'handleUserLogin']31 );3233 $events->listen(34 Logout::class,35 [UserEventSubscriber::class, 'handleUserLogout']36 );37 }38}
If your event listener methods are defined within the subscriber itself, you may find it more convenient to return an array of events and method names from the subscriber's subscribe
method. Laravel will automatically determine the subscriber's class name when registering the event listeners:
1<?php23namespace App\Listeners;45use Illuminate\Auth\Events\Login;6use Illuminate\Auth\Events\Logout;78class UserEventSubscriber9{10 /**11 * Handle user login events.12 */13 public function handleUserLogin($event) {}1415 /**16 * Handle user logout events.17 */18 public function handleUserLogout($event) {}1920 /**21 * Register the listeners for the subscriber.22 *23 * @param \Illuminate\Events\Dispatcher $events24 * @return array25 */26 public function subscribe($events)27 {28 return [29 Login::class => 'handleUserLogin',30 Logout::class => 'handleUserLogout',31 ];32 }33}
1<?php23namespace App\Listeners;45use Illuminate\Auth\Events\Login;6use Illuminate\Auth\Events\Logout;78class UserEventSubscriber9{10 /**11 * Handle user login events.12 */13 public function handleUserLogin($event) {}1415 /**16 * Handle user logout events.17 */18 public function handleUserLogout($event) {}1920 /**21 * Register the listeners for the subscriber.22 *23 * @param \Illuminate\Events\Dispatcher $events24 * @return array25 */26 public function subscribe($events)27 {28 return [29 Login::class => 'handleUserLogin',30 Logout::class => 'handleUserLogout',31 ];32 }33}
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<?php23namespace App\Providers;45use App\Listeners\UserEventSubscriber;6use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;78class EventServiceProvider extends ServiceProvider9{10 /**11 * The event listener mappings for the application.12 *13 * @var array14 */15 protected $listen = [16 //17 ];1819 /**20 * The subscriber classes to register.21 *22 * @var array23 */24 protected $subscribe = [25 UserEventSubscriber::class,26 ];27}
1<?php23namespace App\Providers;45use App\Listeners\UserEventSubscriber;6use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;78class EventServiceProvider extends ServiceProvider9{10 /**11 * The event listener mappings for the application.12 *13 * @var array14 */15 protected $listen = [16 //17 ];1819 /**20 * The subscriber classes to register.21 *22 * @var array23 */24 protected $subscribe = [25 UserEventSubscriber::class,26 ];27}