Laravel: how to create an After or Before save function | update

I need to generate a function to call after or before save () or update (), but I don't know how to do it. I think I need a callback from save () update (), but I don't know how to do this. Thanks

+21
source share
3 answers

Inside your model, you can add the boot () method , which allows you to manage these events.

For example, having the User.php model:

class User extends Model 
{

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

        self::creating(function($model){
            // ... code here
        });

        self::created(function($model){
            // ... code here
        });

        self::updating(function($model){
            // ... code here
        });

        self::updated(function($model){
            // ... code here
        });

        self::deleting(function($model){
            // ... code here
        });

        self::deleted(function($model){
            // ... code here
        });
    }

}

Here you can view all available events: https://laravel.com/docs/5.2/eloquent#events

+64
source

Create a provider using this command

php artisan make:provider ProviderClassName

Model::created(function($model){
  //Do you want to do
});

:

Model::creating(function($model){});
Model::updated(function($model){});
Model::updating(function($model){});
Model::deleted(function($model){});
Model::deleting(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
+7

I don't know if this was available at the time, but today you can use Observers:

https://laravel.com/docs/5.8/eloquent#observers

0
source

Source: https://habr.com/ru/post/1649692/


All Articles