Search code examples
phplaravellaravel-9

Unique always return already taken in laravel validation


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

enter image description here


Solution

  • I think you need to use the same property as the route

    Rule::unique('companies')->ignore($this->company)