laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.62k stars 11.03k forks source link

Registering observers with the ObservedBy attribute does not work as expected #53598

Closed sdkakcy closed 1 day ago

sdkakcy commented 1 day ago

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'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


Screenshot 2024-11-20 at 19 37 38

All traits are looped in the order they are written then calling boot method.

Screenshot 2024-11-20 at 19 34 25

The boot method calls the observe method directly at this point. But the custom trait has not yet been booted and initialised.

Screenshot 2024-11-20 at 19 31 11

https://laravel.com/docs/10.x/eloquent#observers

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.

Thank you in advance

crynobone commented 1 day ago

Can you recheck your Laravel version?

sdkakcy commented 1 day ago

Can you recheck your Laravel version?

Yes of course, it is 10.48.17