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

C4pt4inC's avatar

API Route with session

Hi,

i want to use an api route to set an session value. This should only be available to logged in users. My users got an "api_token" which is send by every ajax request.

It works when i add Session and Cookies to the api-middleware-group like this

'api' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    'throttle:60,1',
    'bindings',
]

In api.php i only add the authentication for that route

Route::group(['middleware' => ['auth:api']], function () {
    
    Route::post('/setSession', ['as'=>'setSession', 'uses'=>'SessionController@index']);

});

I would prefer to set two middleware items - authentication and a group for sessions and stuff. So simple api routes wouldn't have acess to session and so on. But it wont work. After my firt request to that route - i am logged out.

Like this:

Route::group(['middleware' => ['auth:api','loggedInApi']], function () {
    
    Route::post('/setSession', ['as'=>'setSession', 'uses'=>'SessionController@index']);

});

'loggedInApi' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
],  
'api' => [
    'throttle:60,1',
    'bindings',
]
0 likes
0 replies

Please or to participate in this conversation.