Get previous attribute value in Eloquent model event

我的梦境 提交于 2019-12-18 10:15:00

问题


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();
});

回答1:


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)
{
    $original = $user->getOriginal();
    if ($user->username != $original['username']) {
        doSomething();
    }
});

Laravel strikes again!

Be carefult, it ignores the model type casting.




回答2:


In Laravel 4.0 and 4.1, you can check with isDirty() method:

User::updating(function($user)
{
    if ($user->isDirty('username')){
        doSomething();
    }
});



回答3:


You could overload the methods, then call the parent method.



来源:https://stackoverflow.com/questions/17367383/get-previous-attribute-value-in-eloquent-model-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!