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

dust's avatar
Level 9

How to access session variables in API calls

I have a simple application and I want to be able to change language. In my main controller I have:

    session(['applocale' => 'en']);
    $request->session()->put('applocale','en');

I know that these two lines are the same but I want to be sure that they both does not work.

Then I have API method in Language controller:

    public function switchLang(Request $request, $lang)
    {
        error_log("Current language is: " . session('applocale'));
        error_log("Current language is: " . $request->session()->get('applocale'));
    }

And here error_log shows nothing.

That's how it's look like my 'seasons' middleware:

    'sessions' => [
        \Illuminate\Session\Middleware\StartSession::class,
    ]

In Debugbar I can see that my API function has hit both middleware 'api' and 'sessions' but session variables are not in my Language controller.

That's my route:

Route::group(['middleware' => ['sessions']], function () {
    Route::get('lang/{language}', 'LanguageController@switchLang');
});

Any ideas what I'm doing wrong?

0 likes
2 replies
martinbean's avatar

@dust An API is meant to be stateless. The request should include everything it needs to complete that command. If the client needs a response in a specific language, then they should specify the language in the request.

dust's avatar
Level 9

It is stateless. I want to change global language there:

public function switchLang(Request $request, $lang)
{
        if (session('applocale') != $lang) {    
            session(['applocale' => $lang]);
        app()->setLocale($lang);
        }
}

I'm not returning anything from here.

Please or to participate in this conversation.