Skip to content
Advertisement

how to implement laravel validation unique in UpdateRequest custom?

I have a unique rule in file UpdateAnimeRequest, and I want to implement a unique rule like this: https://laravel.com/docs/8.x/validation#rule-unique

The problem is if I want to update without changing the title then the unique error appears, how can I prevent this error from appearing when the user doesn’t want to change the title input field?

Here is the contents of my custom request file:

<?php

namespace AppHttpRequests;

use AppRulesValidGenre;
use AppRulesValidWord;
use IlluminateFoundationHttpFormRequest;
use IlluminateSupportFacadesGate;

class UpdateAnimeRequest extends FormRequest
{
    public function rules()
    {
        return [
            'title' => 'required|unique:animes,title|max:25',
            'genres' => [
                'required', new ValidGenre(), new ValidWord()
            ],
            'status' => 'nullable|regex:/1/',
            'link' => 'nullable|url',
            'motivasi' => 'nullable|regex:/^[a-zA-Z0-9_s-]*$/',
        ];
    }

    public function authorize()
    {
        return Gate::allows('anime_access');
    }
}

Can someone help me to implement ignore self in my custom request?

Advertisement

Answer

first if you want to ignore self then you must have anime_id to know if this have self or not then rule can be

'title' => ['required', "max:25", Rule::unique('animes', 'title')->ignore($this->anime->id, 'id')],
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement