Piotr Nowak
Piotr Nowak

Reputation: 39

Can I have both web and api guards in Laravel?

So far I used API only from website (for AJAX reqeusts), so I applied web middleware, but I'm going to build mobile app using same methods and routes.
I tried to use auth:api middleware on \api\ routes but it forces me to use token in every request.
Is there any way to distinguish what kind of authentication is used then apply proper middleware?

Upvotes: 1

Views: 1142

Answers (1)

Erik Berkun-Drevnig
Erik Berkun-Drevnig

Reputation: 2356

Yes, you can apply different middleware to the same controllers/routes through a different URL.

Assuming Laravel 5.4, then somewhere in your RouteServiceProvider.php:

Route::middleware('web')
     ->namespace($this->namespace)
     ->group(base_path('routes/web.php'));

Route::prefix('api')
     ->middleware(['auth:api', 'web'])
     ->namespace($this->namespace)
     ->group(base_path('routes/web.php'));

Notice that both route groups have the same route file and the same namespace but the second one has a different set of middlewar and a URL prefix.

Upvotes: 1

Related Questions