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

fbc's avatar
Level 2

Is it possible to implement locales without URL prefixes? Maybe through session parameter?

I would like to be able to write functions like the one below that will switch the locale for the users session. I don't know if that is possible yet, or maybe the locale get set and stored in a cookie or something.

    public function en()
    {
        setLocale(en);
        return back();
    }

    public function es()
    {
        setLocale(es);
        return back();
    }

Right now my locales work great except I have to manually go into 'config/app.php' and manually switch the locale variable from 'es' to 'en' when I want to switch. There has got to be an easier way.

0 likes
12 replies
jekinney's avatar

You mean auto detect or allow a user to select?

Both are pretty standard.

fbc's avatar
Level 2

@jekinney Allow user to select. Auto-Detect would be a great second step, but I would happy if I could just get the user to select at the moment.

mercuryseries's avatar

Yes. Usually I use a middleware like:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\{App, Auth, Config, Cookie, Request, Session};

class SetUserLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Get the request language (Ex: http://example.com/fr/bla-bla)
        // You can use a ?lang=fr and change it if you want.
        $urlLanguage = Request::segment(1);
        
        // Get Cookie langugage
        $cookieLanguage = Cookie::get('language');
        
        // Get the Browser Request language
        $browserLanguage = substr(Request::server('HTTP_ACCEPT_LANGUAGE'), 0, 2);

        // Start by checking the request language
        // Check if the request language is supported or not?
        if(!empty($urlLanguage) && in_array($urlLanguage, array_keys(Config::get('your_site.supported_languages'))))
        {
            // Check whether the request url language is not the same as the remembered language in cookies
            if($urlLanguage != $cookieLanguage)
            {
                Session::put('language', $urlLanguage);
            }
            
            // Set the App Locale
            App::setLocale($urlLanguage);
        }

        // Grab the user language in settings if that exists
        else if(Auth::check() && !is_null($userLanguage = Auth::user()->language)) {
            // Set User Language
            App::setLocale($userLanguage);
        }

        // Check if there is a language saved as forever cookie and is it supported or not?
        else if(!empty($cookieLanguage) && in_array($cookieLanguage, array_keys(Config::get('your_site.supported_languages'))))
        {
            // Set App Locale
            App::setLocale($cookieLanguage);
        }

        // Check the browser request language is supported in our app?
        else if(!empty($browserLanguage) && in_array($browserLanguage, array_keys(Config::get('your_site.supported_languages'))))
        {
            // Check whether the request url language is not the same as the remembered language in cookies
            if($browserLanguage != $cookieLanguage)
            {
                Session::put('language', $browserLanguage);
            }
            
            // Set Browser Language
            App::setLocale($browserLanguage);
        }
        else
        {
            // Default Application Setting Language
            App::setLocale(Config::get('app.locale'));
        }

        // Get response in order to set the correct language and return it
        $response = $next($request);
        $language = Session::get('language');
        if(!empty($language))
        {
            // Send the language cookie
            return $response->withCookie(Cookie::forever('language', $language));
        }
        return $response;
    }
}
fbc's avatar
Level 2

@mercuryseries Is there some easy to follow guide anywhere on how to implement this?

By the way I just tried this and it did not work either:

    public function en()
    {
        config(['app.locale' => 'en']);
        return back();
    }

    public function es()
    {
        config(['app.locale' => 'es']);
        return back();
    }
mercuryseries's avatar

@fbc You can put your locale in a session variable and then use it in a middleware.

fbc's avatar
Level 2

@mercuryseries I really appreciate your help, and I am sorry that I am just a beginner and do not fully understand the concept of middleware yet. This is why I wanted the guide. I would not even know where to paste that middleware code. I am pretty sure that you activate all middleware through 'config/app.php', that I can recall doing with a few guide that helped me implement templating stuff for blade.

fbc's avatar
Level 2

Just tried:

    public function en()
    {
        Session::put('locale','en');
        return back();
    }

    public function es()
    {
        Session::put('locale','es');
        return back();
    }

It didn't work either.

fbc's avatar
Level 2

@mercuryseries OK I just created 'App\Http\Middleware\SetUserLanguage.php' and pasted the script. Are there any instructions anywhere that show me how to use it?

mercuryseries's avatar
Level 17

@fbc Sorry for my raw response. Didn't know that you were a beginner. Here is a kind of guide. Hope it helps.

Try this:

// Routes routes/web.php

Route::get('en', function() {
    session(['locale' => 'en']);
    return back();
});

Route::get('es', function() {
    session(['locale' => 'es']);
    return back();
});

// Middleware app/Http/Middleware/SetLocale.php

<?php

namespace App\Http\Middleware;

use Closure;

class SetLocale
{
    protected $supported_languages = ['en', 'es'];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!session()->has('locale')) {
            session(['locale' => $request->getPreferredLanguage($this->supported_languages)]);
        }

        app()->setLocale(session('locale'));

        return $next($request);
    }
}

// Registration App/Http/Kernel.php

Add the middleware to web array in your App/Http/Kernel.php file

        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\SetLocale::class, // here is the line
        ],

Now in order to change the locale you can use for example:

<a href="/en">English</a>
<a href="/es">Spanish</a>
2 likes

Please or to participate in this conversation.