laravel hook into Eloquent pre and post save for every model

前端 未结 3 1880
我寻月下人不归
我寻月下人不归 2020-12-31 13:54

I\'m new to Laravel and ORM\'s in general. How could i hook into Eloquent to fire code before and after a save of any model? I know i can do the following for specific model

3条回答
  •  余生分开走
    2020-12-31 14:19

    There's even a better way of accomplishing this! Create an observer for, lets say a model called House:

    class HouseObserver {
    
        public function saving(House $house) {
            // Code before save
        }
    
        public function saved(House $house) {
            // Code after save
        }
    
    }
    

    Now register the observer with the House model by adding the line House::observe(new HouseObserver) somewhere. The line can be added in the boot method of the model:

    class House extends Eloquent {
    
        // Lots of model code
    
        public static function boot() {
            parent::boot();
            self::observe(new HouseObserver);
        }
    
    }
    

    More info can be found here.

提交回复
热议问题