php 在 Eloquent 模型事件中获取先前的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17367383/
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
Get previous attribute value in Eloquent model event
提问by coatesap
Is there a way to see the old/previous value of a model's attribute in its saving
or updating
event?
有没有办法在其saving
或updating
事件中查看模型属性的旧/先前值?
eg. Is something like the following possible:
例如。是否有以下可能:
User::updating(function($user)
{
if ($user->username != $user->old->username) doSomething();
});
回答by coatesap
Ok, I found this quite by chance, as it's not in the documentation at present...
好吧,我很偶然地发现了这一点,因为它目前不在文档中......
There is a getOriginal()
method available which returns an array of the original attribute values:
有一种getOriginal()
方法可以返回原始属性值的数组:
User::updating(function($user)
{
if ($user->username != $user->getOriginal('username')) {
doSomething();
}
// If you need multiple attributes you may use:
// $originalAttributes = $user->getOriginal();
// $originalUsername = $originalAttributes['username'];
});
Be carefult, it ignores the model type casting.
请注意,它会忽略模型类型转换。
回答by Ola
In Laravel 4.0 and 4.1, you can check with isDirty() method:
在 Laravel 4.0 和 4.1 中,您可以使用isDirty() 方法进行检查:
User::updating(function($user)
{
if ($user->isDirty('username')){
doSomething();
}
});
回答by Half Crazed
You could overload the methods, then call the parent method.
您可以重载方法,然后调用父方法。