I want to register observers on my models. But I don't want to register observers in the boot method of one of your service providers, because it may cost much. I want to register the observer only when I use the model
In document https://laravel.com/docs/5.8/eloquent#observers:
To register an observer, use the observe method on the model you wish to observe. You may register observers in the boot method of one of your service providers. In this example, we'll register the observer in the AppServiceProvider:
There is only example using AppServiceProvider.
In api document https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html#method_observe, there are methods observe and registerObserver. How can I use it?
Just add this into your Model class:
/**
* The "booting" method of the model.
*
* @return void
*/
public static function boot()
{
parent::boot();
static::observe('Your\Observer\Namespace');
}
It will automatically setup the observer the 1st time the model is used (unlike service provider which setups it every time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With