Get previous attribute value in Eloquent model event(在 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
getOriginalignores attribute type casting.
这篇关于在 Eloquent 模型事件中获取先前的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Eloquent 模型事件中获取先前的属性值
基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
