Check for password equality with a custom validation rule in laravel 5.5

smknstd
smknstd
Feb 28 · 2 min read
Photo by Jørgen Håland on Unsplash

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.

A minimalistic form (localized in french) handling an attempt to delete an account with a password which doesn’t match

code16

About open source projects at CODE 16

smknstd

Written by

smknstd

Coder at Code16

code16

code16

About open source projects at CODE 16

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade