Greetings,
In my project I use the following package to make my models archivable: Laravel Archivable
This package fires 4 new events to be used in the corresponding observer class. There is no problem using EventServiceProvider's boot() method to call model's observe method or the $observers property to register the observer, but it does not work as expected when using the ObservedBy attribute. This is because when the HasEvents trait is booted, the observer is registered at that moment. Therefore, even if another bootable trait in the model calls the addObservableEvents method in the initialize method, it will have no effect. Because this operation is done after HasEvents has been booted, the observer is already registered.
Steps To Reproduce
Create a model with an Observer
Create a bootable trait with boot and initialize methods and use it on model
Call addObservableEvents with custom model event names in initialize method
Add ObservedBy attribute to your model for register observer
Take an action that fires the special event you have created
All traits are looped in the order they are written then calling boot method.
The boot method calls the observe method directly at this point. But the custom trait has not yet been booted and initialised.
To register an observer, you may place the ObservedBy attribute on the corresponding model:
....
Or, you may manually register an observer by calling the observe method on the model you wish to observe. You may register observers in the boot method of your application's App\Providers\EventServiceProvider service provider:
Laravel documentation says you can use both. But they give different results for this situation.
Laravel Version
10.48.17
PHP Version
8.2
Description
Greetings, In my project I use the following package to make my models archivable: Laravel Archivable This package fires 4 new events to be used in the corresponding observer class. There is no problem using EventServiceProvider's
boot()
method to call model'sobserve
method or the$observers
property to register the observer, but it does not work as expected when using theObservedBy
attribute. This is because when theHasEvents
trait is booted, the observer is registered at that moment. Therefore, even if another bootable trait in the model calls theaddObservableEvents
method in the initialize method, it will have no effect. Because this operation is done after HasEvents has been booted, the observer is already registered.Steps To Reproduce
addObservableEvents
with custom model event names in initialize methodAll traits are looped in the order they are written then calling boot method.
The boot method calls the observe method directly at this point. But the custom trait has not yet been booted and initialised.
https://laravel.com/docs/10.x/eloquent#observers
....
Laravel documentation says you can use both. But they give different results for this situation.
Thank you in advance