在 Eloquent 模型事件中获取先前的属性值

2021-12-26 00:00:00 php laravel laravel-4 eloquent

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

例如.是否有以下可能:

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.

相关文章