phplaravelapilaravel-passport

Auth guard [:api] is not defined?


When I use auth:api guard for the logout route, I'm facing the following exception:

Auth guard [:api] is not defined

I have already implemented registration/login APIs, but I am facing this error with logout API, which I had protected using auth::api.

config/auth.php:

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

routes/api.php:

Route::group(['prefix' => 'auth'], function () {
    Route::post('login','AuthController@login');
    Route::post('signup','AuthController@signup');

    Route::group(['middleware' => 'auth::api'], function () {
        Route::get('logout','AuthController@logout');
        Route::get('user','AuthController@user');
    });
});

I should be able to log out the user.


Solution

  • You have an extra colon in your code, that's why it is trying to find the guard :api.

    According to the docs:

    Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

    Route::put('post/{id}', function ($id) {
        //
    })->middleware('role:editor');
    

    So in your case it would be:

    Route::group(['prefix' => 'auth'], function () {
        Route::post('login','AuthController@login');
        Route::post('signup','AuthController@signup');
    
        Route::group(['middleware' => 'auth:api'], function () {
            Route::get('logout','AuthController@logout');
            Route::get('user','AuthController@user');
        });
    });