logo
podcast Podcast
get help Get Unstuck

Does listener order matter?

And would I rely on it?

Joel Clermont
Joel Clermont
2025-01-03

In response to my previous tip where I mentioned that I still like manually registering events and listeners, a reader replied with another reason they like manually wiring listeners: you control the order they run in.

I had never thought about this, so the first thing I did was check if this is true. Digging into the Laravel source code, I found that they are executed in the order they are registered.

So it is technically true, with some important caveats:

  1. This is not documented behavior, so it could change in the future. It could even change in a patch release. So if you are relying on this behavior, I'd say you should write a test for it.
  2. The sequencing is only "pure" if none of your listeners are queued. In other words if listener 1 and 2 are both queued, you are not safe to assume that listener 2 would only run after listener 1 finished. Things get even more unpredictable if you have more than one queue as well.

And if you really wanted to go down this path, I'd highly recommend a comment in each listener explaining that if it ever changes to be queued, you need to revisit how it's wired up.

What would I do instead? If the sequence of listeners mattered, and I needed one to start after the other finished, I'd rather just have one listener which then dispatched a job to handle the second part when it was done. Or I'd consider using chained jobs.

That would leave no chance of the order changing and breaking my app.

Here to help,

Joel

P.S. Programming involves tradeoffs and there isn't always a clear answer as to what is the best way to do something. That's why it is valuable to get a variety of opinions in 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.