Decouple your Laravel code using Attribute Events

Getting to work

Store action on the OrderController

Let’s refactor

Method to update stock on the Product model
  • Processing email and calling external systems are not the responsibility of the model.
  • We’ll always have to use the updateStock method to update the stock, which can quickly be forgotten.

Time to decouple

Attribute Events on the Product model
Route events to listeners
  • The model doesn’t have to deal with side effects such as sending emails.
  • If we need to adjust stock in a new place, we don’t have to worry about performing necessary side effects or calling special methods. The listeners will always trigger when the data is updated.
  • If a new requirement arises, only an additional listener needs to be added.
  • The code is nicely decoupled. We can put the listeners anywhere, completely separate from the calling code. Especially useful when using a folder-by-feature structure.
OrderController@store action without side effects
Simple code that doesn’t have to deal with side effects 👌



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store