Home » Php » php – laravel model callbacks after save, before save, etc

php – laravel model callbacks after save, before save, etc

Posted by: admin April 23, 2020 Leave a comment

Questions:

Are there callbacks in Laravel like:

afterSave()
beforeSave()
etc

I searched but found nothing. If there are no such things – what is best way to implement it?

Thanks!

How to&Answers:

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
});

Answer:

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();

Answer:

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
        });
    }

}

Answer:

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… 🙂

Answer:

In Laravel 5.7, you can create a model observer from the command line like this:

php artisan make:observer ClientObserver --model=Client

Then in your app\AppServiceProvider tell the boot method the model to observe and the class name of the observer.

use App\Client;
use App\Observers\ClientObserver;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
   {
        Client::observe(ClientObserver::class);
   }
   ...
}

Then in your app\Observers\ you should find the observer you created above, in this case ClientObserver, already filled with the created/updated/deleted event hooks for you to fill in with your logic. My ClientObserver:

namespace App\Observers;

use App\Client;

class ClientObserver
{

    public function created(Client $client)
    {
        // do your after-model-creation logic here
    }
    ...
}

I really like the simplicity of this way of doing it. Reference https://laravel.com/docs/5.7/eloquent#events

Answer:

If you want control over the model itself, you can override the save function and put your code before or after __parent::save().

Otherwise, there is an event fired by each Eloquent model before it saves itself.

There are also two events fired when Eloquent saves a model.

“eloquent.saving: model_name” or “eloquent.saved: model_name”.

http://laravel.com/docs/events#listening-to-events

Answer:

Your app can break using afarazit solution*
Here’s the fixed working version:

NOTE: saving or any other event won’t work when you use eloquent outside of laravel, unless you require the events package and boot the events. This solution will work always.

class Page extends Eloquent {

   public function save(array $options = [])
   {
      // before save code 
      $result = parent::save($options); // returns boolean
      // after save code
      return $result; // do not ignore it eloquent calculates this value and returns this, not just to ignore

   }
}

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';
if($page->save()){
  echo 'Page saved';
}

afarazit* I tried to edit his answer but didn’t work