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

佐手、 提交于 2019-11-28 04:43:09

Inside your model, you can add a boot() method which will allow you to manage these events.

For example, having 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
        });
    }

}

You can review all available events over here: https://laravel.com/docs/5.2/eloquent#events

Create a provider by using this command

php artisan make:provider ProviderClassName

then define the callbacks for models in boot function

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

List of available callbacks:

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){});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!