Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpMick's avatar
Level 15

API route guest access.

Hi,

I am using Passport to protect my API. I want a route which can be accessed without authentication. How can I do this?

I thought that this would work but it returns Unauthenticated (in api.php):

Route::namespace('\\')->middleware('guest')->group(function () {
	
});

or

Route::namespace('\\')->group(function () {
	
});

I'm surprised at this because I thought that middleware('auth:api') had to be added to protect the routes?

auth.php

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

Cheers,

Mick

0 likes
8 replies
jeffreyvanrossum's avatar

I think your namespace might be invalid. Maybe remove that part and try if it works.

phpMick's avatar
Level 15

No, that would not give me unauthenticated, the route is being found correctly.

jeffreyvanrossum's avatar

Just to clarify, you did edit your code sample after my response. The namespace value first was a back slash\, you've only just escaped it.

But yeah, that would probably have given you a invalid syntax error instead of a un-authenticated message.

Are you pointing to a controller where you are adding some middleware in the constructor perhaps? Or do you have any other active middleware registered in your app that might cause this behavior?

phpMick's avatar
Level 15

Yeah, I only edited it because it was displayed wrong in the markdown. It has always been two slashes , I just added another one to make it visible on here. The routing is working correctly.

No, nothing in the controller (actually an Action but same thing).

Nothing elsewhere, this is a fresh application.

lenineto's avatar

Have you changed your RouteServiceProvider file? It sets the prefix of the namespace to App\Http\Controllers by default. On that same it also sets the "api" prefix and adds middleware('api') to any API routes. It could be a namespace conflict or your routes being re-defined.

phpMick's avatar
Level 15

Nope, not touched RouteServiceProvider.

Tippin's avatar

@phpmick One thing you may want to try, set the guard when using guest. Just like auth:api, try guest:api

Route::namespace('\')->middleware('guest:api')->group(function () {
	
});

jeffreyvanrossum's avatar

Just out of curiosity and slightly off-topic, but what is the value of adding namespace('\\')? That is the default, or am I missing something?

Please or to participate in this conversation.