Laravel更新模型具有唯一的属性验证规则 [英] Laravel update model with unique validation rule for attribute

查看:1229
本文介绍了Laravel更新模型具有唯一的属性验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Laravel 用户模型,它在用户名上有一个唯一的验证规则电子邮件。在我的存储库中,当我更新模型时,我重新验证字段,以便不需要规则验证的问题:

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":["The username has already been taken."],"email":["The email has already been taken."]}

有没有办法修复这个优雅?

Is there a way of fixing this elegantly?

推荐答案

将当前更新的id实例附加到验证器。您可以传递实例的ID以忽略唯一的验证器。在验证器中使用参数来检测您是否正在更新或创建它,并在第一种情况下发送用户ID,然后您可以使用:

Append the currently updating id instance to the validator. You can pass the id of your instance to ignore the unique validator. In the validator use a parameter to detect if you are updating or creating it, and send the user id in the first case, then you can use:

强制一个唯一的规则可以忽略一个给定的ID

'email'=>'unique:users,email_address''$ userId

'email' => 'unique:users,email_address,'.$userId

这篇关于Laravel更新模型具有唯一的属性验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆