skip to Main Content

BadMethodCallException: Method LaravelPassportGuardsTokenGuard::attempt does not exist. in file C:xampphtdocstestpassportapilaravel-backend-apivendorlaravelframeworksrcIlluminateMacroableTraitsMacroable.php on line 112
auth()->guard(‘api’)->attempt($request->only([’email’, ‘password’])))

This is supported passport or not,
because this error shows at my end.
How to solve this?

config->auth.php `page`

        'company' => [
            'driver' => 'session',
            'provider' => 'company_users', // Use the appropriate provider
        ],
        'api' => [
            'driver' => 'passport', // set this to passport
            'provider' => 'company_users',
            'hash' => false,
        ]
 if (Auth::guard('api')->attempt($request->only(['email', 'password']))) {
           $user = Auth::guard('api')->user();
            $token = $logUser->createToken('MyApp')->accessToken;

Its a not working

2

Answers


  1. Laravel passport(TokenGuard) doesn’t have the attempt() method. It uses the OAuth2 token, not the session.


    As you shared, you create your token like this.

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
    
        if (auth()->attempt($credentials)) { // web login
            $user = auth()->user();
            $token = $user->createToken('MyApp')->accessToken;
            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
    }
    

    Then in the config

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users', // **** make sure this is correct(main user model should be here.) you're using `company_users` make sure it's the main user table which uses web login
            'hash' => false,
        ],
    ],
    

    And finally, in your request, if you pass the Authorization header with the Bearer, this will work.

    Make sure your model (in mine users as per your code company_users) has a trait called HasApiTokens

    Login or Signup to reply.
  2. The issue is that attempt is a method of SessionGuard but not TokenGuard.

    If you want to authenticate a user before creating a token for them use the web guard.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search