【问题标题】:Ignore unique validation id on update更新时忽略唯一的验证 ID
【发布时间】:2017-10-05 06:57:01
【问题描述】:

我有一个 CategoryRequest.php 文件和字段“名称”的唯一验证。 当我使用表单创建时,它可以工作,因此它可以防止插入具有相同名称的类别。

问题是当尝试更新它时,会说:“该名称已被占用。”或者如果我尝试下面的代码,它会显示:'未定义变量:id'。

如何更新并且在验证时它会忽略自己的名称? 这是我的代码:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CategoryRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|unique:categories,name,'.$id.',id'
        ];
    }
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    改变这个:

    return [
        'name' => 'required|unique:categories,name,'.$id.',id'
    ];
    

    到这里:

    return [
        'name' => 'required|' . Rule::unique('categories')->ignore('category')
    ];
    

    或者这个:

    return [
        'name' => ['required', Rule::unique('categories')->ignore('category')]
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2014-06-28
      • 1970-01-01
      • 2019-01-10
      相关资源
      最近更新 更多