2
votes

I am trying to check if entered password is currently logged in users password and give error message if not.

I have profile editing form with name, email etc.

Last input in form is password input.

How can I check if password that is entered is current password?

In EditProfileRequest i tried (custom request file, made with artisan):

  public function rules() {
    return [
        'first_name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users,email,'.Auth::user()->id,
        'country_code' => 'digits_between:1,4|numeric',
        'phone' => 'digits_between:5,12|numeric',
        'password' => 'required|confirmed',
    ];
}

but it rejected form with correct password. Then I tried adding to controller this part:

if (!Hash::check(Input::get('password'), Auth::user()->password)) {
        return Redirect::back()->withInputs();
    }

this worked but I don't get any errors for user and I don't know how to add custom error messages, since I am using built-in validator.

2
So at the end I used: if (!Hash::check(Input::get('password'), Auth::user()->password)) { return Redirect::back()->withErrors(['password' => 'Incorrect password']); }Riiwo

2 Answers

2
votes

You can pass the custom error message as following.

$validator = Validator::make(Input::all(), $rules);
//Here you are checking your inputs with the validation rules that you are created. 

if ($validator->fails())
{
    //If the validation fails, check for the password validation too and return the error. 
    if (!Hash::check(Input::get('password'), Auth::user()->password)) {
        return Redirect::back()
                          ->withInputs()
                          ->withErrors(['login' => 'Your custom Error Msg'])
                          ->withErrors($validator);
    }
    else{
               return Redirect::back()
                          ->withInputs()
                          ->withErrors(['login' => 'Your custom Error Msg']);
   }
}

As a short answer for your question to get a custom error message:

return Redirect::back()->withInputs()->withErrors(['login'=>'custom msg']);
0
votes

Also make sure you display the errors in your login page.

@if (count($errors) > 0)
<div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

You can check displaying validation errors on this page https://laravel.com/docs/5.2/validation#quick-displaying-the-validation-errors