沃梦达 / 编程问答 / php问题 / 正文

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

Get previous attribute value in Eloquent model event(在 Eloquent 模型事件中获取先前的属性值)

本文介绍了在 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.

这篇关于在 Eloquent 模型事件中获取先前的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Eloquent 模型事件中获取先前的属性值

基础教程推荐