phplaravelmodel

Take an action after any model is created, updated, or deleted in Laravel


I want to execute a function every time ANY model is created, updated, or deleted in my application.

For example, I want to print the model name and its record data to my log.

How can I do this? I've been looking for some class to extend, but haven't had any luck.


Solution

  • Answering to your comment on Robok's answer, you can have a BaseObserver.

    As example, here is the one I use:

    <?php namespace App\Observers;
    
    use Illuminate\Database\Eloquent\Model as Eloquent;
    
    class BaseObserver {
    
        public function saving(Eloquent $model) {}
    
        public function saved(Eloquent $model) {}
    
        public function updating(Eloquent $model) {}
    
        public function updated(Eloquent $model) {}
    
        public function creating(Eloquent $model) {}
    
        public function created(Eloquent $model) {}
    
        public function deleting(Eloquent $model) {}
    
        public function deleted(Eloquent $model) {}
    
        public function restoring(Eloquent $model) {}
    
        public function restored(Eloquent $model) {}
    }
    

    Now any model observer can extend it:

    <?php namespace App\Observers;
    
    use App\Observers\BaseObserver;
    
    class ProductObserver extends BaseObserver {
    
        public function creating(Eloquent $model)
        {
            $model->author_id = Sentry::getUser()->id;
        }
    
        public function created(Eloquent $model)
        {
            if(Input::hasFile('logo')) Image::make(Input::file('logo')->getRealPath())->save(public_path() ."/gfx/product/logo_{$model->id}.png");
        }
    
        public function updating(Eloquent $model)
        {
            $model->author_id = Sentry::getUser()->id;
        }
    
        public function updated(Eloquent $model)
        {
            if(Input::has('payment_types')) $model->paymentTypes()->attach(Input::get('payment_types'));
    
            //Upload logo
            $this->created($model);
        }
    }
    

    If you want to have something like $model->author_id = Sentry::getUser()->id in every observer, you can of course apply that in the BaseObserver.