Form validation is an essential part of Laravel development. One common requirement is to ensure a field’s value is unique within a database table. Laravel offers the unique validation rule to easily achieve this.
To validate the uniqueness of a field, simply add the unique rule in the validation logic, for example:
$request->validate([
'email' => 'unique:users',
]);
This checks whether the email value already exists in the users table, and returns a validation error if it does.
When updating user information, you may want to allow the user to keep their original email address. You can exclude the current record’s ID from the uniqueness check like this:
$request->validate([
'email' => 'unique:users,email,' . $user->id,
]);
This validation ignores the record with $user->id and checks uniqueness only among other records.
When users register or change their password, it’s common to require entering the password twice to confirm. Laravel provides the confirmed rule to simplify this process.
Simply add confirmed to the field’s validation rules, for example:
$request->validate([
'password' => 'required|confirmed',
]);
This rule automatically checks if password matches password_confirmation, and triggers a validation error if they don’t match.
When implementing password update functionality, besides validating the new password, you need to verify the user’s old password and impose security requirements on the new password.
An example of a robust password update validation looks like this:
$request->validate([
'old_password' => 'required',
'new_password' => 'required|min:8|different:old_password',
'confirm_password' => 'required|same:new_password',
]);
Where:
These rules help improve the security of the password update process and reduce user errors.