Search code examples
laravelhashbcrypt

Laravel - Hash check returns false even when its correct


I was using md5 to login from a form and I am trying to switch to bcrypt, but the Hashk::check method always returns false, even if the password is correct, any idea why it is not working?

         $email = Input::get('email');
         $password =  Input::get('password');
         $user = User::where("email","=",$email)->first();

            if(Hash::check($password,$user->password)) {

                    $userID = $user->id_user;
                    $username = $user->first_name." ".$user->last_name;
                    $admin = "yes";
                    Session::put('userID',$userID);
                    Session::put('userName',$username);
                    Session::put('admin',$admin);
                    return redirect('/cw-admin/');
            } else {
                    return Redirect::to('/cw-admin/login')
                        ->withErrors(['no' => 'Incorrect password']);
            }
            }

EDIT added the User model, I only changed the fillables, primaryKey and ID, the methods are left empty.

class User extends Model implements Authenticatable
{

    protected $table = 'user';
    protected $primaryKey = 'id_user';

    protected $fillable = [
        'first_name','last_name','password','email'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
    }

dd output:

User {#592 ▼
  #table: "user"
  #primaryKey: "id_user"
  #fillable: array:4 [▼
    0 => "first_name"
    1 => "last_name"
    2 => "password"
    3 => "email"
  ]
  #hidden: array:2 [▼
    0 => "password"
    1 => "remember_token"
  ]
  #connection: "mysql"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▶]
  #original: array:7 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}

Solution

  • You have to check your User table definition. If Hashed field is returning false even if you are posting something to it, it is not retrieving the same value as the one you have posted.

    In my case, I would use max length on column(s) that store hashed values.

    Alter Table Users Modify password VCHAR(255);