Owen Conti

How to Handle Multiple Events with a Single Listener in Laravel

Posted on under Laravel by Owen Conti.

Laravel provides a simple way to declare event listeners out of the box via the  EventServiceProvider class.

Here's a quick example:

1<?php
2 
3class EventServiceProvider extends ServiceProvider
4{
5 /**
6 * The event listener mappings for the application.
7 *
8 * @var array
9 */
10 protected $listen = [
11 LoginEvent::class => [
12 HandleLoginListener::class
13 ],
14 ];
15}

With the above, anytime the  LoginEvent is fired, the  handle() method of the  HandleLoginListener class will be called. Pretty simple, right?

But what if you have dozens or even hundreds of events that you want to all go through the same handler?

One option would be to list them out individually in the  EventServiceProvider class.

Yikes! What if you forget to add the listener when you add a new event?

Another option would be to listen to an interface, and have your events implement the interface.

Here's an example interface:

1// App\Events\NotifiableEvent.php
2 
3<?php
4 
5namespace App\Events;
6 
7interface NotifiableEvent
8{
9 /**
10 * Returns the display name of the event.
11 *
12 * @return string
13 */
14 public function getEventName(): string;
15 
16 /**
17 * Returns the description of the event.
18 *
19 * @return string
20 */
21 public function getEventDescription(): string;
22}

And here's an example event, that implements the interface:

1// App\Events\CreatedApplicationMember.php
2 
3<?php
4 
5namespace App\Events;
6 
7class CreatedApplicationMember implements NotifiableEvent
8{
9 public function getEventName(): string
10 {
11 return 'Created Application Member';
12 }
13 
14 public function getEventDescription(): string
15 {
16 return 'Fired whenever a new Application Member is added to your Application.';
17 }
18 
19 // constructor and stuff goes here...

Then in  EventServiceProvider, you can listen for the interface instead of the specific event classes:

1<?php
2 
3class EventServiceProvider extends ServiceProvider
4{
5 /**
6 * The event listener mappings for the application.
7 *
8 * @var array
9 */
10 protected $listen = [
11 NotifiableEvent::class => [
12 SendEventNotification::class
13 ],
14 ];
15}

Now anytime an event that implements the NotifiableEvent interface is dispatched, the  SendEventNotification listener will be called.


Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on X!

Found an issue with the article? Submit your edits against the repository.