All developers must have come across this situation where you have to manage a unique field, where the table column accepts only unique values. One of the most use cases is
users table where we accept unique values for
Laravel provides and easy way where you can define unique fields when you create the migration files as shown below.
... $table->unique('username'); $table->unique('email'); ...
When the fields are defined this way, the field only accepts unique fields and will give an error when you try to enter a value that is already exists in the field.
In Laravel, we can use validation methods to check whether the field contains the value user just passed. The following validation will check for the unique values. Please note that I am using Laravel Livewire.
$this->validate([ 'username' => 'required|alpha_num|unique:users', 'email' => 'required|email|unique:users', ]);
The problem with above validation rules is that even if the owner of the username or email tries to update their profile information, it will give the same error stating that the username or email already exist.
To overcome this issue we have to tweak the validation rules a little bit. The unique validation rule in Laravel accepts an
except parameter where you can pass a variable where Laravel will omit the row while validating. This way the rule will pass for the logged in user. See the below code where I am passing the
user id as except parameter.
$this->validate([ 'username' => 'required|unique:users,username,'.$this->user->id, 'email' => 'required|email|unique:users,email,'.$this->user->id, ]);
Hope this helps for anyone trying to create a profile update page in their web apps.