【问题标题】:Laravel form validation request unique ignorant doesn't work on updateLaravel 表单验证请求唯一无知在更新时不起作用
【发布时间】:2020-07-07 22:14:48
【问题描述】:

我正在尝试更新具有验证所需的唯一名称的数据。但是,我无法让它工作,因为它一直告诉我The name has already been taken.。已经试过了

请看一下我的验证脚本:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RequestDepartment 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 [
            'division_id' => 'required|numeric',
            'name' => "sometimes|required|string|unique:departments,name,{$this->id},id",
            'description' => 'sometimes|nullable|string'
        ];
    }
}

另外,我的控制器的更新脚本:

/**
 * Update the specified resource in storage.
 *
 * @param  \App\Http\Requests\RequestDepartment  $request
 * @param  \App\Department  $department
 * @return \Illuminate\Http\Response
 */
public function update(RequestDepartment $request, Department $department)
{
    $department->update($request->validated());
    $department = Department::whereId($department->id)->with('division')->first();

    return response()->json([
        'updated' => true,
        'data' => $department,
    ]);
}

我正在使用 Laravel 7.x,请问有什么建议吗?

编辑

我想更新 division_iddescription 字段。

编辑 2

我的表单是动态的,在 Vue 实例和 Form 类中

data() {
  return {
    form: new Form({
      division_id: "",
      company_id: "",
      name: "",
      description: ""
    }),
    updateForm: new Form({
      division_id: "",
      company_id: "",
      name: "",
      description: ""
    }),
    filter: ""
  };
},

【问题讨论】:

  • 我不确定,但sometimesrequire,我知道文档使用这种情况......但它很奇怪
  • sometimesrequired 表示如果提供了name 字段,则它应该是必需的并且必须经过验证。在这种情况下,我已经告诉框架无论如何都跳过给定的id,我在使用 laravel 6.x 的旧项目上进行了比较,它可以工作。 7.x 可能有变化?
  • 如果您想更新division_iddescription 而您不需要name,只需创建一个新的RequestUpdateDepartment
  • 如果不设置required,则不会验证name 字段?我还在 5.8 上,不知道新功能。
  • 已验证但未验证required,您可以在其上插入NULL 或空字符串

标签: php laravel


【解决方案1】:

试试这个,

'name' => "required|string|unique:departments,name,". $id,

这里的 $id 表示您要更新的 id。这将检查所有名称数据的唯一部分,但不检查此 ID。

【讨论】:

  • 谢谢,但 $id 未定义,我使用的是表单请求验证器,而不是在控制器中对其进行硬编码
  • 我只是说$id ..你使用你的动态id...为此.....你需要更新哪个id
  • 我试过了,没有任何反应。就像"{$this-id}" 一样
  • 他将id 放在帖子正文中,他需要与$request-&gt;input('id') 一起接受吗?
  • 我错了,应该是company_id,我确实改了,还是不行..:/
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 2021-08-07
  • 2023-03-27
  • 2018-06-26
  • 2020-06-18
  • 2019-11-11
  • 2022-01-21
  • 2020-12-25
相关资源
最近更新 更多