[11.x] Fix ObservedBy Attribute that did not take custom observables in account #50540
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hello laravel team !
I made this pull request to fix the issue described here
Bug description
When using PHP Attribute
ObservedBy
to observe my model (instead of register the observer in theEventServiceProvider
), "custom" observables added through theinitialize{Trait}
usingaddObservableEvents
are not taken in account.(when I use
EventServiceProvider
to register the observer, it works well).my investigation :
When using
ObservedBy
, "custom" observables are not registered because when entering inHasEvents::observe
for the first time, the Model is booting (and already tagged as booted inModel::$booted
). And the instanciated model inHasEvents::observe
line 67 ($instance = new static;
) will not boot the model because it is already booting.Conversely when we register the observer in
EventServiceProvider
we directly callHasEvents::observe
and the previously mentioned$instance = new static;
boot the model and can register "custom" observables.Steps To Reproduce
create a model that use
ObservedBy
create a trait that use
addObservableEvents
create the observer
MyObserver
finally call
fireFoo
Solution found
Do not make the trait
HasEvents
bootable by removingbootHasEvents
.And just call
HasEvents::observe
at the very end ofbootTraits
method.This way all stuff that need to be initialized will be initialized before the model instantiation in the method
HasEvents::observe