I'm trying to update a company data using CompanyRequest
but got an error. Please see my code below and other details.
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');
Error
CodePudding user response:
I think you need to use the same property as the route
Rule::unique('companies')->ignore($this->company)
CodePudding user response:
Try something like
'name' => 'unique:companies,name,' . $id,
so basically name
is unique, but allow update when id is same.
CodePudding user response:
To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
'name' => 'unique:companies,column,'.$this->id