3

I have a form which has an input name. I want to update a database table through that form. The only condition is, the name must be unique. So this is what I did for validation in the backend:

$this->validate($request, [
    'name' => 'required|unique:myTableName'
]);

It's working as expected. It throws this error "The name has already been taken." when I try to enter a name which already exists in the database. But the problem I have with this is, when I'm updating the same entry from database without any change (I.E. I go to edit form, do nothing, update the form), it shows me the same error. In this case, I don't want the error as I'm updating the same value. How can I achieve this with laravel validation?

1

2 Answers 2

3

You have to use following code

$this->validate($request, [
    'name' => ['required', Rule::unique('myTableName')->ignore($yourVariable->id)],
]);

Add header section below code

use Illuminate\Validation\Rule;

More Details here

Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass the table id, to ignore that field from validation

'name' => 'required|unique:myTableName,name,' . $table->id,

With custom Rule :

use Illuminate\Validation\Rule;

'name' => ['required', Rule::unique('myTableName', 'name')->ignore($table->id)],

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.