【问题标题】:Laravel unique validation fails on updateLaravel 唯一验证在更新时失败
【发布时间】:2019-02-26 12:33:08
【问题描述】:

我正在使用 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

【问题讨论】:

  • 有两列一是分支,一是分支名称这是什么?
  • @Gurpalsingh.branches 是表名
  • 'branch_name'=>'required|max:255|unique:branches,branch_name,'.$this->id.',id'
  • $this->id是否等于数据库中要更新的列的id?!
  • @MohamedEmad.yes 你是正确的它的主键

标签: php laravel laravel-5


【解决方案1】:

这样就可以了:

 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 Validation unique

希望这会有所帮助。

【讨论】:

  • $this->route('branch') 是什么意思
  • 示例:Route::post('office-by-company/{company}', 'OfficeController@officeByCompany');请参阅“公司”路由参数,如果您使用不同的路由参数,则相应更改
【解决方案2】:

唯一:表、列、除外、idColumn

验证中的字段在给定的数据库表中必须是唯一的。如果未指定column 选项,将使用字段名称。

validation

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

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

【讨论】:

【解决方案3】:

试试这个

 use Illuminate\Validation\Rule;


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

【讨论】:

  • signh .它会在新记录上失败,即使我添加已经存在的分支名称也会插入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2014-06-28
  • 2018-08-09
  • 2014-08-20
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多