Laravel: Validating Optional Password Change
August 22, 2019
This will make it optional for the user to change their password.
This blog is proudly sponsored by Datsi - Your Personal Database | Visit Datsi.io and learn more
If any of the password fields are filled:
- All of the password fields must be filled.
- The current password must be correct.
- The new password must be confirmed.
- The new password is different than the current password.
- The new password is min. 8 chars.
If none of the password fields are filled, validation will pass.
Rules
Edit your validation rules and add this:
return [
'current_password' => [
'nullable', 'string', 'required_with:new_password,new_password_confirmation',
new PasswordMatch
],
'new_password' => 'nullable|required_with:current_password,new_password_confirmation|string|min:8|different:current_password',
'new_password_confirmation' => 'same:new_password',
];
Of course you can change the min:8
to whatever you like.
The reason I use same:new_password
instead of confirmed
, is to show the error message on the confirmation
field - instead of the new_password
field.
Validation Rule Class
Now we need a validation rule class to make sure the current_password
value is correct.
Run php artisan make:rule PasswordMatch
Edit the file to this: (phpdocs removed for simplification)
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class PasswordMatch implements Rule {
public function __construct() {}
public function passes($attribute, $value) {
return Hash::check($value, Auth::user()->password);
}
public function message() {
return 'Incorrect password.';
}
}
Saving the New Password
Now we know if any of the password fields are filled, the user wants to change their password.
So a simple check to see if 1 of the fields are filled, we have to hash and save the new password:
// ...
if ($request->filled('new_password')) {
$user->password = Hash::make($request->new_password);
}
$user->save();