skip to Main Content

in my project I have two guards, the first is "web" related to admins table with session driver, and the second one is "mobile" related to users table with token driver.

'defaults' => [
    'guard' => 'web',
    'passwords' => 'admins',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'mobile' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

Note: I am using sanctum authentication system.

so I am trying to log in using the second guard and when I attempt credentials, an error occurs:

public function login(Request $request)
{
   .............

     if(!Auth::guard('mobile')->attempt($request->only(['email', 'password']))){
        return response()->json([
           'status' => false,
           'message' => 'Email & Password does not match with our record.',
       ], 401);
     }
        
   .............

}

the error:

"Call to undefined method IlluminateAuthTokenGuard::attempt()"

So how can I check the credentials of non-default guard, or if there is any suggestion ?

2

Answers


  1. Chosen as BEST ANSWER

    @sanjog-karki your solution worked for me, but I tried another solution which is by duplicating the "mobile" guard and setting the driver of the new guard to be: "session", so I can use Auth::guard("new-guard")->attempt($credintials) without any problem.

        'mobile' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'mobile-api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
    

    so now I can check the credentials like this:

    if(!Auth::guard('mobile')->attempt($request->only(['email', 'password']))){
    
       ........
    
    }
    

    and I can use it in middleware like this:

    Route::middleware('auth:mobile-api')->group(function () {
       .......
    });
    

    I will stick with this solution unless something went wrong.


  2. if you are using sanctum then you can do like this

    public function login(Request $request)
        {
            $user= User::where('email', $request->email)->first();
                if (!$user || !Hash::check($request->password, $user->password)) {
                    return response([
                        'message' => ['These credentials do not match our records.']
                    ], 404);
                }
            
                 $token = $user->createToken('my-app-token')->plainTextToken;
            
                $response = [
                    'user' => $user,
                    'token' => $token
                ];
            
                 return response($response, 201);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search