Compare a string with an encrypted password in Laravel.

Ariel Mejia Dev
Ariel Mejia Dev
Published in
2 min readSep 4, 2019

In some cases you need to compare a string given by a user with some password stored and encrypted in the database, the typical case is to auth a user from an API.

Get the string:

To get the string from the request I am going to use the “$request” this request can be place as param with the class “Illuminate\Http\Request”, this is an object and it have properties, you only need to use the arrow notation to get the value of the property.

$request->password;
$request->email;

Get user model by DB:

I create a method call “validate” but it can be anyother name, it get two params email and password with the “request” object, so you need to get the user model from the DB, I prefer to use eloquent, to get the user by email.

And if user is different from null, it returns a comparePassword method:

public function validates(string $email, string $password){$user = User::where(['email' => $email])->first();if (! is_null($user)) {  return $this->comparePasswords($password, $user);}

Compare the string with the DB password value:

The “comparePasswords” method get password as string and the user model fetch from the DB, so I only need to compare the string “password” with the property “password” of the “User” model, to compare those I use the “getAuthPassword” method, this method is define in “User” model in, “Illuminate\Auth\Authenticatable”.

public function comparePasswords(String $password, User $user){   if (Hash::check($password, $user->getAuthPassword())) {      return response()->json([        'authenticated' => true,        'data' => [          'id' => $user->id,        ]      ]);  }}

“getAuthPassword” returns the password from “User” model hashed, but Why not just get the property like: “$user->password()”, by default the “User” model have the password value as hidden:

/*** The attributes that should be hidden for arrays.** @var array*/protected $hidden = ['password', 'remember_token',];

So to preserve the value password as hidden and just get password this time, the “getAuthPassword” is a good way to resolve the problem.

Thanks for reading…

--

--

Ariel Mejia Dev
Ariel Mejia Dev

Fullstack Web/Mobile Developer and Laravel enthusiast.