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']);
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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 ?
@duddy67 Ah, got it. The api middleware is what sets the user to the $request.
Try this:
auth('api')->check()
// and
auth('api')->user();
Please or to participate in this conversation.