ikartik90
ikartik90

Reputation: 2815

Hash::check not returning appropriate result

I have a users table which stores registered users' username, email, password. Passwords are hashed via Hash::make() function before being saved into their respective table records.

I'm attempting to manually create an AuthController module from scratch.

In my authenticate() function, I'm checking if the password entered by the user attempting to the login matches the hashed password corresponding to the username as follows:

public function authenticate(AuthRequest $request)
{
    $hashedPassword = User::where('name', $request->name)
        ->select('password')
        ->get();

    $auth = Hash::check($request->password, $hashedPassword);

    //Die dumping just to check if the hash check has worked
    dd($auth);
}

Here, AuthRequest is the Request class that validates the form input before passing the $request variable to the authenticate() function.

Now, unfortunately, the Hash::check() function isn't responding as expected. I am, as coded above, trying to verify whether the password entered by the user in the login form matches the hashed password in the database table. But despite entering the same password as the hashed password the $auth variable receives a false value.

Upvotes: 1

Views: 103

Answers (2)

nathanmac
nathanmac

Reputation: 455

Change get to first to return the first item not the collection

$user = User::where('name', $request->name)
    ->select('password')
    ->first();

$hashedPassword = $user->password;

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219910

get returns a collection. To get the value directly, use the value method:

$hashedPassword = User::where($request->only('name'))->value('password');

Read the docs, under the section title Retrieving A Single Row / Column From A Table.


P.S. If you're using an older version of Laravel, that method was called pluck.

Upvotes: 2

Related Questions