I need to generate a function to call after or before save() or update() but i don't know how to do. I think I need a callback from save() update() but I don't know how to do. Thanks
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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){});