【发布时间】: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_id 或 description 字段。
编辑 2
我的表单是动态的,在 Vue 实例和 Form 类中
data() {
return {
form: new Form({
division_id: "",
company_id: "",
name: "",
description: ""
}),
updateForm: new Form({
division_id: "",
company_id: "",
name: "",
description: ""
}),
filter: ""
};
},
【问题讨论】:
-
我不确定,但
sometimes和require,我知道文档使用这种情况......但它很奇怪 -
sometimes和required表示如果提供了name字段,则它应该是必需的并且必须经过验证。在这种情况下,我已经告诉框架无论如何都跳过给定的id,我在使用 laravel6.x的旧项目上进行了比较,它可以工作。7.x可能有变化? -
如果您想更新
division_id或description而您不需要name,只需创建一个新的RequestUpdateDepartment -
如果不设置
required,则不会验证name字段?我还在 5.8 上,不知道新功能。 -
已验证但未验证
required,您可以在其上插入NULL或空字符串