Inigo EC
Inigo EC

Reputation: 2328

Laravel route in multiple middelwares

I want to have the same route within the auth:api middleware, and also out of it.

Right now, if I include it in both, only the one out of the auth:api is taken into consideration, even if the user is logged in.

Is there a way that if the user is logged in it goes to auth:api and if not it goes out of any middleware?

The reason to do this is that if the user is logged in, I want to access user information, and for that it needs to go through the auth:api.

Upvotes: 1

Views: 132

Answers (2)

Rwd
Rwd

Reputation: 35190

As long as you're including the token in the request, you will be able to get access to the current User.

Out-of-the-box, Laravel will set the default guard to be web. When you place routes under the auth middleware it will set the default guard to be whatever is passed to the middleware i.e. when you have auth:api it will set the default guard to be api for that request.

If you want to be able to access the User without it being under the auth:api middleware, you will simply need to be explicit with what guard should be used e.g.

auth('api')->user(); // or Auth::guard('api')->user();

The same applies for check():

auth('api')->check(); // or Auth::guard('api')->check();

or if you're using the Request object:

$request->user('api'); // or request()->user('api');

Upvotes: 3

Mix Cap
Mix Cap

Reputation: 3

It 's not possible to have multiple same routes in your application and work independently. Laravel will match the first one that it find in your routes map.

Create one route and check for authentication in your controller.

if (Auth::check()) {
    // The user is logged in...
}

Upvotes: -1

Related Questions