Laravel:如何在保存|更新之后或之前创建函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38685019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: how to create a function After or Before save|update
提问by Daniele Longheu
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
我需要生成一个函数在 save() 或 update() 之后或之前调用,但我不知道该怎么做。我想我需要从 save() update() 回调,但我不知道该怎么做。谢谢
回答by Mauro Casas
Inside your model, you can add a boot()method which will allow you to manage these events.
在您的模型中,您可以添加一个boot()方法,该方法将允许您管理这些事件。
For example, having User.php model:
例如,拥有 User.php 模型:
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
您可以在此处查看所有可用事件:https: //laravel.com/docs/5.2/eloquent#events
回答by Rohit Khatri
Create a provider by using this command
使用此命令创建提供程序
php artisan make:provider ProviderClassName
then define the callbacks for models in boot function
然后在 boot 函数中定义模型的回调
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){});