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

SanaeK's avatar

Persist locale in both web and api routes

I store my locale in a session, every request I run a Localization middleware to set the locale stored in the session.

This works fine between web requests, but I have an api request which validates fields on a form and returns a list of validation messages. Of course, the session which was set in the web routes cannot be known by the api routes, so I cannot set locale using the same middleware.

How would you suggest persisting the locale so it can be used both by web and api routes?

0 likes
2 replies
krisi_gjika's avatar

what are you using the locale on a api request, validation messages? anyhow each user can have a preferred locale on the DB or you can send the locale via a header.

martinbean's avatar

@sanaek APIs are typically stateless. If you want to set the locale based on the user’s preferences then you can try using the HTTP header specifically for this: Accept-Language.

Grab the preferred language from the request, and set the application locale for that request. You can do this in your web route group as well:

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        $locale = match ($preferredLanguage = $request->preferredLanguage) {
            '*' => app()->getLocale(), // Any locale, so use application default
            default => $preferredLanguage,
        };

        app()->setLocale($locale);

        return $next($request);
    }
}

Please or to participate in this conversation.