Search code examples
laravellaravel-8laravel-validation

Laravel unique validation, only if value is different & without id


I am trying to update the data and to do this I am using a method patch on my form.

Update Validation Request

use Illuminate\Validation\Rule;

'question' => [
    'required',
    'string',
    Rule::unique('faqs_questions','question'),
    'max:30',
],

If there are no changes in my question it gives me an error:

The question has already been taken.

dd($this->toArray()) on validation request gets me below output:

array:9 [▼
    "_method" => "PATCH"
    "_token" => "LLqlQfMpzSdyAInVOaqs5lqBMbEvNT9eMDU9ZZxJ"
    "my_name_TOApMPqqwwBasdts9bLa" => null
    "valid_from" => "eyJpdiI6IkJ2TUpZV29ZV0Qzasdasdaasgst5345wtgrtyegq4yhq4qhgqgMDU1"
    "question" => "Question B"
    "answer" => "Answer B"
]

I tried using Rule::unique('faqs_questions','question')->ignore($this->question), on my request file but I think it needs id which we don't have in any inputs. Is there any way to resolve it?


Solution

  • You could do the following which uses a where clause to say we want to check the question is not already in the table.

    $validator = Validator::make(['question' => $request->question], [
        'question' => [ 
            'required', 
            'string',
            Rule::unique('faq_questions')->where('question', '!=', $request->question),
            'max:30'
        ]
    ]);
    

    You can change the field it checks against to be whatever you want, hopefully the above gives you the general idea.

    Then you can check if validation was successful or unsuccessful:

    if ($validator->fails()) {
       // error
    }