0

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 Illuminate\Auth\TokenGuard::attempt()"

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

2 Answers 2

0

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);
    }
0

@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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.