本文介紹了在 Eloquent 模型事件中獲取先前的屬性值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
有沒有辦法在 saving
或 updating
事件中查看模型屬性的舊/以前值?
例如.是否有以下可能:
User::updating(function($user){if ($user->username != $user->old->username) doSomething();});
解決方案
好吧,我是偶然發現的,因為它目前不在文檔中...
有一個 getOriginal()
方法可以返回原始屬性值的數組:
User::updating(function($user){if ($user->username != $user->getOriginal('username')) {做一點事();}//如果你需要多個屬性,你可以使用://$originalAttributes = $user->getOriginal();//$originalUsername = $originalAttributes['username'];});
<塊引用>
小心,在 Laravel 7 之前 getOriginal
忽略屬性類型轉換.
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...
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 careful, prior to Laravel 7
getOriginal
ignores attribute type casting.
這篇關于在 Eloquent 模型事件中獲取先前的屬性值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!