Laravel 5.8 setLocale globally
Asked Answered
K

3

5

I have a route:

    Route::get('/setlocale/{locale}', function($locale) {
            App::setLocale($locale);

            return back();
    })->name('setlocale');

When I go to: example.com/setlocale/ro I return back to page. But language is not changed. Why? I get always language en. I check language with:

    app()->getLocale();

But I need set language globally for application.

Katabolism answered 26/3, 2019 at 9:25 Comment(5)
in config/app.php change the 'locale' value as you want.Sickener
@Sickener I need change locale with route on web, but not in config.. ThanksKatabolism
App::setLocale($locale); is per request, so you have to call it even in the back() routeSickener
Possible duplicate of Laravel change locale not workingFaith
@Katabolism if you got answered then marks your answer as accpeted answer so this question will not populate in unanswered questionsEster
E
20

Try this way

1. When user choose a language we put our selected locale(language) in session [example en, fr, hi ]


Route::get('setlocale/{locale}',function($lang){
       \Session::put('locale',$lang);
       return redirect()->back();   
});

2. We use a middleware for translating pages according to our session locale (user selected)

<?php

namespace App\Http\Middleware;

use Closure;
use Session;
use App;
use Config;
class LanguageSwitcher
{
    /**
     * 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::put('locale', Config::get('app.locale'));
        }
        App::setLocale(Session::get('locale'));
        return $next($request);
    }
}

3. We put this middleware in kernel.php routeMiddleware (app/Http/kernel.php)

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'language' => \App\Http\Middleware\LanguageSwitcher::class,        
    ];
'language' => \App\Http\Middleware\LanguageSwitcher::class,

4. For serving this middleware we need route group. so each request goes through this middleware

Route::group(['middleware'=>'language'],function ()
{
    //your translation routes
});

Logic in middleware

In middleware for every request we check if locale set in current session or not. if Session not having locale then for current request we set locale to config locale means in your app configuration locale

'locale' => 'en',  // config/app.php
 Session::put('locale',Config::get('app.locale')); // in middleware code we use Config method to get app configuration locale
App::setLocale(Session::get('locale')); // finally set this to App locale

else if we have locale in current session then we set that to App locale

App::setLocale(Session::get('locale')); // set this to App locale

Complete Article and Source Code - www.ultimateakash.com

Ester answered 26/3, 2019 at 9:36 Comment(2)
Please add some explanation to your code such that others can learn from itNoun
@NicoHaase Thanks for your suggestion. now explanation addedEster
C
2

It'll only be set for that current request. You're calling the back() method, which will start a new request/response, and will reset the locale.

You should persist the value to the users session, or cookie, then use a service provider, or middleware to set the locale from the session/cookie.

Route::get('/setlocale/{locale}', function (\Illuminate\Http\Request $request, $locale) {
    $request->session()->put('locale', $locale);
    // or
    session(['locale' => $locale]);

    return back();
});


// Middleware:

public function handle($request, $next) {
    App::setLocale($request->session->get('locale', 'some default locale');

    // or

    App::setLocale(session('locale'));

    return $next($request);
}

Hope that helps.

Helpful links:

Coston answered 26/3, 2019 at 9:30 Comment(2)
Session store not set on request. Error with middleware.Katabolism
You may need to use the session helper method, or Session facade in that case.Coston
S
0

I was facing the same problem, the locale was changing in session but not in config. So have checked the session's locale in every blade and controller and set the default the language instant from there, here is the code on my blade file

@php

if(\Session::get('locale') == 'en') 
    \App::setLocale('en');
else                                
    \App::setLocale('bn');

@endphp

Hope it will help you

Steinway answered 13/5, 2020 at 1:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.