Laravel JWTAuth::attempt suddenly returning False

Viewed 168

I'm having a problem that came out of nowhere. I created a login function using JWTAuth and it was working pretty well, the JWTAuth::attempt returns the token that I needed. But after I added the Auto-Hash password function in the User Model, the JWTAuth::attempt always returns false.

I also added softDeletes in the user migration. What causes the JWTAuth::attempt keeps returning false? Because I didn't modify anything except the User Model and the User Migration. How can I fix this problem?

Here is my codes:

  1. Auto-Hash Password Function (User.php Model)
    public function setPasswordAttribute($password)
    {   
        $this->attributes['password'] = Hash::make($password);
    }
  1. Login Function (AuthController.php Controller)
public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        
        try {
            $token = JWTAuth::attempt($credentials);
            return response()->json(['status' => 'success','token' => $token], 200);
        } catch(Exception $e){
            return response()->json(['error' => $e], 401);
        }
    }
1 Answers

You may use for checking credentials.

    $credentials = $request->only('email', 'password');

    if (false === ($token = JWTAuth::attempt($credentials))) {
        return response()->json(['status' => 'error'], 400);
    }         
 
    return response()->json(['status' => 'success', 'token' => $token], 200);

Also, just use auto-hash inside your controller or in your service. Maybe your setPasswordAttribute function has some side effects.

Related