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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:45:39  来源:igfitidea点击:

Get previous attribute value in Eloquent model event

phplaravellaravel-4eloquent

提问by coatesap

Is there a way to see the old/previous value of a model's attribute in its savingor updatingevent?

有没有办法在其savingupdating事件中查看模型属性的旧/先前值?

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.

您可以重载方法,然后调用父方法。