Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel hook into Eloquent pre and post save for every model

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 models but i'm looking at figuring out how to do this for every model.

class Page extends Eloquent {

   public function save()
   {
      // before save code 
      parent::save();
      // after save code
   }
}
like image 217
David Avatar asked Feb 15 '13 19:02

David


1 Answers

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.

like image 96
Niklas Ekman Avatar answered Oct 16 '22 19:10

Niklas Ekman