logo
podcast Podcast
get help Get Unstuck

When should you use events and observers?

Laravel events and observers seem to do very similar things. So when would you use one over the other?

Joel Clermont
Joel Clermont
2023-08-24

When should you use an event in your application? Personally, we use them quite sparingly. If there's some work we want to defer outside the current request, we will usually dispatch that as a job. But one scenario where we issue events is when two or more separate things need to react to what happened.

For example, let's say when a user signs up for our application, they also buy some "tokens" to use different features of the app. That would require a call to our payment provider. But we also have a third-party CRM where we track the lifetime purchases of a user across more than one application. That would require a separate call to the CRM. Instead of packaging up two totally separate concepts into a single job, we instead fire a TokenPurchase event which has two separate listeners.

Now let's think about observers. They're essentially events fired by your model where all the "listener" logic is packaged up into a single Observer class. So when would you reach for that instead?

Again, we use observers sparingly, but in cases where you want to enforce some logic every time a model is created, updated, etc, and you want this to happen in real-time, they're a good choice.

For example, as a user performs certain actions in our app, they spend their available tokens. We maintain a token balance, so an observer can fire every single time a token is spent (or refunded), and whether this happens in controllers, commands, our Nova admin panel, or a Tinker session, we know that logic will be universally enforced.

Want to know what happens when the user spends their last token? Stay tuned for tomorrow's email...

Here to help,

Joel

P.S. You think this tip is good? You should try our free book of even more Laravel tips to make your application a little bit better.

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.