DolDurma
DolDurma

Reputation: 17299

Laravel use Hash as Validator

i'm using Hash::check() to check current password with entered password. i use this if for check this action

$HashPassowrd = Hash::make(Input::get('password'));

if( ! Hash::check( Input::get('currPassword') , $data->password ) )
{
   return Redirect::to('profile.update')
            ->withErrors('Current Password in Incorrect!');
}

how to use that as validator ? for example in this rules

$rules = array(
            'name'        => 'required|alpha',
            'family'      => 'required',
            'email'       => 'required|email',
            'currPassword'=> 'required',
            'password'    => 'required|confirmed',
            'password_confirmation'=>'required',
        );

Upvotes: 3

Views: 8206

Answers (3)

George
George

Reputation: 734

Since Laravel 6.x a password validation rule is added that will do the above for you.

Check its documentation

simply add this rule to your validation rules :

'password' => 'password:api'

where api is the authentication guard

Upvotes: 0

Alfonso Bribiesca
Alfonso Bribiesca

Reputation: 41

You also can use a closure validation rule:


    [
        'currPassword' => function ($attribute, $value, $fail) {
            if (! Hash::check($value, $this->user()->password)) {
                $fail('Your current password doesnt match');
            }
        },
        'password' => 'required|min:6|confirmed',
    ];

Upvotes: 3

The Alpha
The Alpha

Reputation: 146191

You can add custom rule in to the validator:

Validator::extend('checkHashedPass', function($attribute, $value, $parameters)
{
    if( ! Hash::check( $value , $parameters[0] ) )
    {
        return false;
    }
    return true;
});

Now you can use this custom rule as:

'currPassword' => 'required|checkHashedPass:' . Input::get('currPassword')

So, if the validation fails for this rule then you'll get error messages for this in your view and can access using $errors->first('currPassword'); but you need to pass a custom error message for this custom rule you've created using:

$messages = array( 'currPassword.checkHashedPass' => 'Current Password failed!' );

So, during validation you have to pass the $messages array using:

$validator = Validator::make(Input::all(), $rules, $messages);

Check custom validation rules on the documentation.

Upvotes: 9

Related Questions