A
A
Artemmmm132021-02-01 14:54:03
Laravel
Artemmmm13, 2021-02-01 14:54:03

How to properly use unique rule in Laravel custom request classes?

It is necessary to process the field with the unique rule, except if an update occurs. That is, if some entity changes, check for uniqueness and throw an error if the field with this value already exists, but if the same model changes, then it turns out that it also falls under this rule and an error is thrown. How to fix it ?
Tried like this:

public function rules()
    {   
        return [
            'title' => "required|min:3,max:255|unique:audiobook_genres,id",
            'slug' => "required|min:3,max:255|unique:audiobook_genres,id",
        ];
    }

So:
public function rules()
    {   
        return [
            'title' => "required|min:3,max:255|unique:audiobook_genres,id,".$this->id,
            'slug' => "required|min:3,max:255|unique:audiobook_genres,id,".$this->id,
        ];
    }

And also tried this:
public function rules()
    {   
        return [
            'title' => "required|min:3,max:255|unique:audiobook_genres,title,".$this->title,
            'slug' => "required|min:3,max:255|unique:audiobook_genres,slug,".$this->slug,
        ];
    }

But nothing helped, so what is the right way to use this rule in the case of updating the model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
netrox, 2021-02-01
@Artemmmm13

Rule::unique('audiobook_genres')->ignore((int) $this->id);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question