Laravel 雄辩的变异器不适用于更新数据

2024-03-29

我的模型中有用于数据库表字段中的哈希/重新哈希数据的访问器和修改器。例如:

public function setFullNameAttribute($value)
{
    $this->attributes['full_name'] = Helper::geted('encrypt', $value);
}

public function getFullNameAttribute($value)
{
    return Helper::geted('decrypt', $value);
}

当我将数据保存到数据库时,所有发送数据都以散列形式保存,但更新数据时不进行散列。我的保存/更新代码:

$profile = [
    'full_name' => "John",
    'address' => "United Kingdom"
];

$profile_save = new Profile($profile);
$exist = Personal::where('user_id', Auth::id())->count();
if($exist == 0) $user->profile()->save($profile_save);
if($exist == 1) $user->profile()->update($profile);

When I 第一次将此信息保存到数据库:

When I 第二次输入当前 URL 数据将被更新:

enter image description here Why does not the information be stored in an encrypted form when updating information?


你的问题在这一行:

$user->profile()->update($profile);

修改器和访问器在 eloquent 上工作,而不是在查询构建器上工作。您正在使用更新函数,这是一个查询生成器函数,因此您正在直接更新数据库。 用这个:

$profile = [
    'full_name' => "John",
    'address' => "United Kingdom"
];
$profile = auth()->user()->profile;
if ($profile) {
    $profile->full_name = $profile['full_name'];
    $profile->address = $profile['address'];
    $profile->save();
} else {
    auth()->user()->profile()->create($profile);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 雄辩的变异器不适用于更新数据 的相关文章