When should you use events and observers?


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...

Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.