首页 > 解决方案 > Laravel 唯一验证在更新时失败

问题描述

我正在使用 laravel 5.7 并使用表单请求,但我的数据库中有一个唯一的 branch_name 以及唯一的 slug,但每次更新验证错误 .branch 名称已经存在

public function rules()
{

    switch($this->method()) {

    case 'DELETE':
        return [
            'slug'=>'required',

        ];
    case 'POST':
    case 'PUT':
    case 'PATCH':
        return [
            'branch_name'=>'required|max:255|unique:branches,branch_name,id'.$this->id,
            'branch_address'=>'required',

        ];
    default:
        break;
    }
}

我也尝试了以下但没有用

'branch_name'=>'required|max:255|unique:branches,branch_name,'.$this->id,

'branch_name'=>'required|max:255|unique:branches,branch_name,slug'.$this->slug,

我对 id 和 slug 都有一个隐藏的值,即使我在规则方法上打印,我也可以看到 id 和 slug

标签: phplaravellaravel-5

解决方案


这将做:

 use Illuminate\Validation\Rule;

'branch_name' => [
    'required|max:255',
    Rule::unique('branches')->ignore($this->route('branch')),
]

用您的 web.php 编辑路由中的路由参数名称替换“分支”。

您可以在添加和编辑两者中使用此验证。

如果您的数据库字段名称不同,则将该名称作为忽略函数中的第二个参数发送。喜欢

Rule::unique('branches')->ignore($this->route('branch'), 'branchName'),

详细信息:Laraval 验证独一无二

希望这可以帮助。


推荐阅读