在Eloquent模型事件中获取先前的属性值 [英] Get previous attribute value in Eloquent model event
本文介绍了在Eloquent模型事件中获取先前的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在其saving
或updating
事件中查看模型属性的旧/先前值?
Is there a way to see the old/previous value of a model's attribute in its saving
or updating
event?
例如可能出现以下情况:
eg. Is something like the following possible:
User::updating(function($user)
{
if ($user->username != $user->old->username) doSomething();
});
推荐答案
好吧,我很偶然地发现了这一点,因为它目前不在文档中.
Ok, I found this quite by chance, as it's not in the documentation at present...
有一个getOriginal()
方法可用,该方法返回原始属性值的数组:
There is a getOriginal()
method available which returns an array of the original attribute values:
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.
这篇关于在Eloquent模型事件中获取先前的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文