laravel model callbacks after save, before save, etc

Actually, Laravel has real callback before|after save|update|create some model. check this:

https://github.com/laravel/laravel/blob/3.0/laravel/database/eloquent/model.php#L362

the EventListener like saved and saving are the real callbacks

$this->fire_event('saving'); 

$this->fire_event('saved');

how can we work with that? just assign it to this eventListener example:

 \Laravel\Event::listen('eloquent.saving: User', function($user){
  $user->saving();//your event or model function
});

Adding in an example for Laravel 4:

class Page extends Eloquent {

    public static function boot()
    {
        parent::boot();

        static::creating(function($page)
        {
            // do stuff
        });

        static::updating(function($page)
        {
            // do stuff
        });
    }

}

Even though this question has already been marked 'accepted' - I'm adding a new updated answer for Laravel 4.

Beta 4 of Laravel 4 has just introduced hook events for Eloquent save events - so you dont need to extend the core anymore:

Added Model::creating(Closure) and Model::updating(Closure) methods for hooking into Eloquent save events. Thank Phil Sturgeon for finally pressuring me into doing this... :)


The best way to achieve before and after save callbacks in to extend the save() function.

Here's a quick example

class Page extends Eloquent {

   public function save(array $options = [])
   {
      // before save code 
      parent::save($options);
      // after save code
   }
}

So now when you save a Page object its save() function get called which includes the parent::save() function;

$page = new Page;
$page->title = 'My Title';
$page->save();

Tags:

Php

Laravel