Courses

Eloquent: The Expert Level (Laravel 9)

Model Observers and Their Methods

Previous: WasCreated, IsDirty and Other Checks If Model Was Changed
avatar

I am currently working on a tournament app and I've made an observer for Games so when a game is created, determine the winner, update the standings table, etc. Since you mention only the CRUD methods for the observer, where will all other logic should be correctly placed? I just created several private methods and added them under the same GameObserver...

avatar

That depends.

For your case, I would write a Job which would be triggered as soon as a winner has to be selected. That job would run in the Queue (which would not slow down the application for you) and proccess anything you need.

Observers are meant for CRUD actions and anything else could fit in these:

  • Jobs - Custom create jobs and trigger them manually when needed.
  • Events - Dispatch events when something happens. This will be automatically listened for.

But it all depends on your application and it's needs. So hopefully this helps you!

avatar

Thanks for your answer! So the winner gets dynamically selected from the result of the game creation. There is no a manual way to "select the winner". Do you still think it still fit under Jobs? or it makes more sense to dispatch events instead? I'll also need to handle the scenearios of draw (1 point to each team)

avatar

Jobs/Events are similar in their capabilities, but one of them can be automatically triggered (events). Which would be best for your case - I'm not sure. I would just pick one and see how it feels. From there, if needed, you can always switch them

avatar
You can use Markdown
avatar
You can use Markdown