Answer the question
In order to leave comments, you need to log in
Laravel Events vs Model Observers?
Where is the best place to put a trigger on an action. Of course, there are a lot of options, Laravel provides Model Observers and Events for this case .
And yet, there are Queues jobs, commands, services and a couple more goodies if you dig through the docks.
I'm a bit confused about what to use and when, since both options give the desired result. Example, the user finishes editing the post, this can be added to the Observer function updated or Events - PostUpdated event. And actually put it in the action log.
On the one hand, the Observer does not have a user entry and exit event, it was possible to add something like that. On the other hand, Events are more global, I think it would be possible to write everything at once in Events, but why then Observers? And besides, you can do the same with the help of magic methods, hook the events of creating, deleting, etc., objects.
So what to use?
Answer the question
In order to leave comments, you need to log in
Use both, but clearly separate the actions in these methods.
Personally, I use Observer for internal operations with the model before writing to the database (-ing methods). To, for example, generate data or create a related service model. That is, those things that are directly related to the life of this model. But I use Event in order to perform some external work on notification, for example, or on running commands. The simplest example: a user is created, when saving, a certain token is generated for him in the creating method for something necessary. After saving, in created , the associated model is generated with service information and the CreatedEvent event is thrown. And inside the CreatedEventHandler event, I start sending notifications.
UPD: And since you specified the Log tag , then logging actions with the model is just better to be placed in the Observer , as well as checking the rights to perform actions with it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question