A scenario using events and observers together


Yesterday we walked through an example application dealing with users and tokens, and illustrated when we would use an event versus an observer.

Today, we'll expand on that example and talk about a use case for using events and observers together.

What happens in our application when a user spends their last token? The app is set up to automatically purchase their next block of tokens, which will require upstream calls to our payment provider to complete the purchase and to our CRM to update the user's lifetime value.

We might be tempted to do this extra logic right inside the observer when we first detect the token count is now 0. But this is happening inside a user request, and those upstream API calls could take a couple seconds to complete. We don't want to slow down the user's experience for some logic that could be deferred until after the request is complete. So here's a perfect use case for issuing our TokenPurchase event from within the observe method.

This way we don't slow down the user, and we can reuse the existing listeners we have in place to handle the payment and CRM calls.

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.