logo
podcast Podcast
get help Get Unstuck

Be careful about duplicating events

This bit me on a recent Laravel 11 upgrade

Joel Clermont
Joel Clermont
2024-12-24

Ever since Laravel introduced automatic event discovery, I've still preferred to manually register my events and listeners.

Events and listeners already tend to be a little bit "hidden" in an app, but at least with manual registration in the EventServiceProvider, you have one place to look to see what's going on at a high level.

In Laravel 11, as part of the "slimming" to one service provider, another change was introduced which turned event discovery on by default. More significantly, this new default comes into effect even if you don't slim your Laravel 10 app, leaving the EventServiceProvider in place.

Why is this a problem?

With the new default on top of my manual wiring, an event gets registered to the same listener twice: once from my manual wiring, and another time from the discovery which relies on the parameter type-hint in my listener. This means the code in those listeners actually runs twice. Definitely not good!

I don't see it mentioned in the docs, but you can still alter this new default behavior:

// app/Providers/EventServiceProvider.php
public function boot()
{
    static::disableEventDiscovery();
}

With that one line change, we were no longer accidentally running the listeners twice.

Here to help,

Joel

P.S. At the beginning of the original Zelda game, Link gets a sword from a guy who says "It's dangerous to go alone! Take this." That's a good metaphor for software development too, which is why we created the Mastering Laravel community.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.