How to handle multiple events with a single listener in Laravel

Published under Laravel.

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

Here's a quick example:

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:

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

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

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


Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0