Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to usr use the observe method on the model?

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?

like image 764
TechRex Avatar asked Oct 27 '25 18:10

TechRex


1 Answers

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).

like image 82
Shizzen83 Avatar answered Oct 29 '25 09:10

Shizzen83



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!