唯一始终 return 已接受 laravel 验证
Unique always return already taken in laravel validation
我正在尝试使用 CompanyRequest
更新公司数据,但出现错误。请在下面查看我的代码和其他详细信息。
CompanyRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class CompanyRequest 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()
{
if($this->isMethod('PATCH')) {
return [
'name' => [
'required',
'max:255',
Rule::unique('companies')->ignore($this->id)
],
'owner' => 'required|max:255',
'address' => ''
];
}
return [
'name' => 'required|max:255|unique:companies',
'owner' => 'required|max:255',
'address' => ''
];
}
}
CompanyController.php
public function update(Company $company, CompanyRequest $request)
{
return $company->update($request->validated());
}
api.php
Route::patch('company/{company}', [CompanyController::class, 'update'])->name('company.update');
错误
我认为你需要使用与路线相同的属性
Rule::unique('companies')->ignore($this->company)
试试
'name' => 'unique:companies,name,' . $id,
所以基本上 name
是唯一的,但是当 id 相同时允许更新。
要告诉唯一规则忽略用户的ID,您可以将ID作为第三个参数传递:
'name' => 'unique:companies,column,'.$this->id
我正在尝试使用 CompanyRequest
更新公司数据,但出现错误。请在下面查看我的代码和其他详细信息。
CompanyRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;
class CompanyRequest 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()
{
if($this->isMethod('PATCH')) {
return [
'name' => [
'required',
'max:255',
Rule::unique('companies')->ignore($this->id)
],
'owner' => 'required|max:255',
'address' => ''
];
}
return [
'name' => 'required|max:255|unique:companies',
'owner' => 'required|max:255',
'address' => ''
];
}
}
CompanyController.php
public function update(Company $company, CompanyRequest $request)
{
return $company->update($request->validated());
}
api.php
Route::patch('company/{company}', [CompanyController::class, 'update'])->name('company.update');
错误
我认为你需要使用与路线相同的属性
Rule::unique('companies')->ignore($this->company)
试试
'name' => 'unique:companies,name,' . $id,
所以基本上 name
是唯一的,但是当 id 相同时允许更新。
要告诉唯一规则忽略用户的ID,您可以将ID作为第三个参数传递:
'name' => 'unique:companies,column,'.$this->id