Jack The Baker
Jack The Baker

Reputation: 1903

Laravel Auth guard [api] is not defined

Laravel 8.83.19
Passport 10.4

Simply started a new project and installed passport and want to use middleware for a route but give this error:

Auth guard [api] is not defined

auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],

AuthServiceProvider.php

 public function boot()
    {
Passport::routes();
}

User Model

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
...

User Controller

class UserController extends Controller
{
    public function index(Request $request)
    {
        return User::all();
    }

Api.php

Route::middleware('auth:api')->group(function () {
    Route::get('/user/index', [UserController::class, 'index']);
});

But when I run http://localhost:8000/api/user/index give me:

InvalidArgumentException: Auth guard [api] is not defined. in file D:\Workshop\Other\xxx\xxxapi\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 84

ofcourse I cleared cache:

Route::get('/clear', function() {

    Artisan::call('cache:clear');
    Artisan::call('config:clear');
    Artisan::call('config:cache');
    Artisan::call('view:clear');
    Artisan::call('route:cache');

    return "Cleared!";
});

By run this:

http://localhost:8000/clear

Upvotes: 0

Views: 3366

Answers (2)

amirrezasalari
amirrezasalari

Reputation: 82

Your auth.php file must be like this :

<?php
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
            ]
    ]
?>

Upvotes: 4

amirrezasalari
amirrezasalari

Reputation: 82

You need to clear config cache to take effect. for Unauthenticated it means token is not valid or is not passed correctly

https://laravel.com/docs/5.7/passport#passing-the-access-token

Upvotes: 0

Related Questions