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

Bhargav960143's avatar

Single API use for authenticated and guest user

My laravel application route configured on routes/api.php is.

<?php
use Illuminate\Http\Request;
Route::post('see_all_product',  'API\ProductController@see_all_product');
?>

Issue is i want to sent list of product but if user authenticated then send product favorite flag 1, and if not authenticated then send return favorite 0

But both case send product list with favorite flag.

If i logged in with my user id and password and send request for see_all_product that time i m getting blank user.

$user = $request->user();

But if i set route like below i m getting user details.

<?php
use Illuminate\Http\Request;
Route::group(['middleware' => 'auth:api'], function(){
        Route::post('see_all_product',  'API\ProductController@see_all_product');
});
?>

Now issue is how can i get details if authorization set in the header with same api.

<?php
use Illuminate\Http\Request;
Route::post('see_all_product',  'API\ProductController@see_all_product');
?>

API is same for both authenticated and guest user.

Please guide me where i can miss something?

0 likes
3 replies
aurawindsurfing's avatar

Hi @bhargav960143

Your api routes should have nothing to do with you user being logged in or not.

API requests should be authenticated by a token here is more info about it: https://laravel.com/docs/master/api-authentication

So in your case if there is no token then you will send favorite = 0 always in response, if there is a verified token then you send back favorite = 1 in your response plus rest of the data.

Nothing to do with user being logged in.

Hope it helps!

raihaiiuc's avatar
$middlewares = \Request::header('Authorization') ? ['auth:api'] : [];

Route::middleware($middlewares)->group(function () {
    Route::get('/demo/{id}', [App\Http\Controllers\DemoController::class,'demoIndex']);
});

you can use this for check and apply middleware .

Please or to participate in this conversation.