Check for password equality with a custom validation rule in laravel 5.5
EDIT: Since version 6.x, a new built-in validation rule is available, check it out.
When letting a user change his password or deleting his account, you might ask him to give his old password (for security reason). Laravel doesn’t offer this functionality to check the given password value out of the box. The good news is there are plenty of easy ways to implement it yourself. This article gives a great explanation of how to solve it with a custom validation rule and the Hash facade. But it was written 3 years ago, and there has been water under the bridge. In 2017 laravel introduced custom validation rules. And here’s how you could use it for checking if the user password match the hashed version stored in database.
To generate a new rule object, you may use the make:rule
Artisan command.
php artisan make:rule ValidCurrentUserPassword
Then simply use the Hash facade to check the given value against the hashed value you stored.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;
class ValidCurrentUserPassword implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return Hash::check($value, auth()->user()->password);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Given password does not match';
}
}
Then you might use the custom rule in your controller validation like:
/**
* Delete User Account
* @return \Illuminate\View\View
*/
public function destroy(Request $request)
{
$request->validate([
'password' => [
'required',
new ValidCurrentUserPassword()
]
]);
...
}
That’s it! You‘re now able to check old password as any other form field.