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

duddy67's avatar

An API route accessible for both authenticated and unauthenticaded users ?

I set up an api authentication as explained here: https://laravel.com/docs/6.x/api-authentication. Then in my api routes:

Route::group(['middleware' => 'auth:api'], function () {
    Route::apiResource('posts', PostController::class);
});

And everything works as expected.

However, I need the api.index route to be accessible for both authenticated and unauthenticaded users.

App\Http\Controllers\Api\Blog\PostController@index

If users are authenticated they can see all the posts, if they're not they only see the public posts. How can I do that ? Should I overwrite the auth:api middleware, create a custom middleware, modify the index route ?

0 likes
7 replies
Nakov's avatar

You could exclude the index from the apiResource:

Route::get('posts', [PostController::class, 'index']);

Route::group(['middleware' => 'auth:api'], function () {
    Route::apiResource('posts', PostController::class)->except(['index']);
});
1 like
duddy67's avatar

@Nakov Thanks, it was as simple as that. But now how can I check whether the user is authenticated in my index method ?

duddy67's avatar

@Nakov Well, it looks like $request->user() always returns null even when the bearer token is sent...

Nakov's avatar
Nakov
Best Answer
Level 73

@duddy67 Ah, got it. The api middleware is what sets the user to the $request.

Try this:

auth('api')->check()

// and 

auth('api')->user();
1 like

Please or to participate in this conversation.