Lubomir Stankov
Lubomir Stankov

Reputation: 179

Laravel localization does not work: locale isn't changed

I'm trying to make localization with Laravel, but my code doesn't work, some opinion or advices?

Here is the code:

My Language middleware handle() method:

public function handle($request, Closure $next)
{
    if(Session::has('locale')) {
        $locale = Session::get('locale', Config::set('app.locale'));
    } else {
        $locale = "bg";
    }

    App::setLocale($locale);

    return $next($request);
}

My controller method:

public function changeLang(Request $request,$lang) {
    if (!empty($request)) {
        Session::put('locale',$lang);
    } else {
        Session::set('locale',$lang);
    }
    return back();
}

And here is my route:

Route::get('/{lang}','LanguageController@changeLang');

What am I doing wrong?

Upvotes: 2

Views: 2672

Answers (2)

M Arfan
M Arfan

Reputation: 4575

Hope this code will work for you.

Controller

   public function index($locale) 
  {
      session(['locale' => $locale]);
      App::setLocale($locale);
      return Redirect::back();
   }

Language Middleware:

public function handle($request, Closure $next)
    {
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        else { // This is optional as Laravel will automatically set the fallback language if there is none specified
            App::setLocale(Config::get('app.fallback_locale'));
        }
        return $next($request);
    } 

Route:

Route::get('/{lang}', 'LanguageController@index');

Last add your Langauge middleware in app/Http/Kernal.php in middlewaregroup

 \App\Http\Middleware\Language::class,

Upvotes: 6

Lubomir Stankov
Lubomir Stankov

Reputation: 179

I fixed it by adding my middleware in middleware groups!

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\Language::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

Upvotes: 2

Related Questions