36

In laravel I want to check if user enter current password than check with that password which is store in database in that user data. If correct than continue otherwise give message Password is incorrect.

I am new in laravel so not getting exact idea for this.

Thanks in advance.

$('#pwd').blur(function(){
            var oldpwd=$('#pwd').val();
            var uid = $('#id').val();
            console.log(uid);
            if(oldpwd != "")
            {
              $.ajax({
                  url : "{{ url/profile/checkOldPwd}}",
                  data : { oldpwd:oldpwd , uid:uid },
                  type : "POST",
                  success : function(data) {
                    if(data == 0){
                      $("#msg-old").show();
                      $("#msg-old").html("Password is Incorrect!");
                      $("#pwd").val("");
                      $("#pwd").focus();
                  }
                  else
                  {
                    $("#msg-old").hide();
                    $("#msg-old").html("");
                  }
                }
                });
              }
            });
3
  • I just try using ajax but not getting how to check with so can you give some idea? Commented Jul 22, 2016 at 5:33
  • Check documentation link for more info regarding authorization or show us your code to help you. Commented Jul 22, 2016 at 5:47
  • Above is my ajax code. Commented Jul 22, 2016 at 5:53

9 Answers 9

96

As Hiren has mentioned you can use the default registered hasher as that is passed to the specific UserProvider used. The default is Illuminate\Hashing\BcryptHasher.

You can use it a couple of ways:

  1. Out of the container
$user = User::find($id);
$hasher = app('hash');
if ($hasher->check('passwordToCheck', $user->password)) {
    // Success
}
  1. Using the Facade
$user = User::find($id);
if (Hash::check('passwordToCheck', $user->password)) {
    // Success
}
  1. Out of interest using the generic php function password_verify also works. However that works because the default hashing algorithm it uses is bcrypt.
if (password_verify('passwordToCheck', $user->password)) {
    // Success
}
Sign up to request clarification or add additional context in comments.

5 Comments

Which do you prefer? Is out of the container the most elegant/fastest?
Personally I more and more prefer the out of the container (1)
@LeonVismer What if the existing password hash stored in the database needs to be rehashed?
@KiranManiya If the work factor was adjusted one can use Hash:needsRehash($hashed) to check for that.
@LeonVismer Yup, I got it. I updated the answer as well.
7

you can use hash:check method.

create password using hash:

$password = Hash::make('secret');

check password:

if (Hash::check('secret', $hashedPassword))
{
    // The passwords match...
}

Comments

6

When the user attempts to access the page, redirect them to an auth page.

Do the ajax call then do the following in your php:

public function check(Request $request)
{
    if(Hash::check($request->password, $user->password)) {
        // They match
    } else {
        // They don't match
    }
}

I havn't tested this so it might not work.

2 Comments

This won't work. Bcrypt returns different string every time, it is not like md5
@Dastur thank youuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu💕💕💕💕💕💕💕💕💕💕💕💕💕💕💕💕💕
5

Wow it's actually super simple:

$request->validate([
     'password' => 'required|string|password',
]);

The field under validation must match the authenticated user's password.

However for people in the future:

This rule was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Password rule instead.

So it's

$request->validate([
     'password' => 'required|string|current_password',
]);

Source

Comments

3

Password is correct or not , authenticate password in laravel PHP: Just do it

public function authenticateEmployee(array $data){

 $email = $data['email'];
 $password = $data['password'];
 $user = User::where('email', '=', $email)->first();   //get db User data   

 if(Hash::check($password, $user->password)) {   
      return response()->json(['status'=>'false','message'=>'password is correct']);
    } else {
        return 'false';
    }
}

Hit upvote :) Please

1 Comment

Maybe it's a better practice to get the email like this $data->get('email') instead of $data['email']?
2

None of the answers have mentioned that where is Hash class located! We first need to use Hash

use Illuminate\Support\Facades\Hash;

Now we can use check method

Hash::check($request->password, $user->password)

Comments

1

if (Hash::check($request->password, Auth::user()->password)) { //Sucess }

Comments

1

The authentication logic in laravel 6.* is in "vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php". In this file, you'll find sendFailedLoginResponse() method, which we are going to override on LoginController.php

protected function sendFailedLoginResponse(Request $request)
    {

        if (!User::where('email', $request->email)->first()) {
            throw ValidationException::withMessages([trans('auth.email')]);
        }
        
        if (!User::where('email', $request->email)->where('password', bcrypt($request->password))->first()) {
            throw ValidationException::withMessages([trans('auth.password')]);
        }
    }

This custom method verifies if a user is present on the database, looking for the unique value that you set up on your model. If the user is present on the database, the password is checked. Then, you can call the errors with

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

</div>

@endif

on your blade file. Remember that you call those auth.* files from "resources\lang\en\auth.php"

Comments

0
  1. Hit the server route with your AJAX call.
  2. Check the result of auth()->attempt($request->only('email', 'password'))
  3. Return JSON back with a message and HTTP status code (200 if it is successful, 400 if it failed).
  4. Show the message in the success() method to a div. If it is an error, show the error message inside the error() method to a div.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.