Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation throws error on updating same unique value

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?

like image 921
Rifat Bin Reza Avatar asked Feb 01 '26 19:02

Rifat Bin Reza


1 Answers

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

like image 164
A.A Noman Avatar answered Feb 03 '26 08:02

A.A Noman