Laravel 更新模型,具有唯一的属性验证规则 [英] Laravel update model with unique validation rule for attribute
问题描述
我有一个 Laravel User
模型,它在 username
和 email
上有一个唯一的验证规则.在我的存储库中,当我更新模型时,我会重新验证字段,以免出现所需规则验证的问题:
I have a Laravel User
model which has a unique validation rule on username
and email
. In my Repository, when I update the model, I revalidate the fields, so as to not have a problem with required rule validation:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray());
$user->save();
return $user;
}
测试失败:
ValidationException: {"username":["用户名已经"],email":[电子邮件已经被接收."]}
ValidationException: {"username":["The username has already been taken."],"email":["The email has already been taken."]}
有没有办法优雅地解决这个问题?
Is there a way of fixing this elegantly?
推荐答案
将当前正在更新的实例的 id
附加到验证器.
Append the id
of the instance currently being updated to the validator.
传递实例的
id
以忽略唯一验证器.
在验证器中,使用参数来检测您是更新还是创建资源.
In the validator, use a parameter to detect if you are updating or creating the resource.
如果更新,强制唯一规则忽略给定的id:
If updating, force the unique rule to ignore a given id:
//rules
'email' => 'unique:users,email_address,' . $userId,
如果创建,照常进行:
//rules
'email' => 'unique:users,email_address',
这篇关于Laravel 更新模型,具有唯一的属性验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!