Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot switch language in Laravel 4

I tried routing to switch language but there's no change. Could you help me, pls?

Route::get('lang/{lang}', function($lang)
{
    App::setLocale($lang);
    return Redirect::to('/');
});
like image 664
Oc Chuoj Dau Avatar asked May 15 '13 07:05

Oc Chuoj Dau


People also ask

How do I change my locale in laravel?

Laravel's gives you the option to change the locale for a single Http Request by executing the setLocale method on App Facade App::setLocale($locale); , But what if once the language is changed you don't want to worry about setting the Locale and this should be taken care by an automatic code logic.

How do I get laravel locale?

To fetch current locale you should use App::getLocale() or App::isLocale('...') . Localization. You can also use app()->getLocale() which in Blade would be {{ app()->getLocale() }} .


1 Answers

App::setLocale() is not persistent - that is to say that it will not remember between requests what you have stored. Instead you could use the session to remember the chosen locale, and read from the session the locale on each request. We can also read the default locale (from config) in case there isn't one set in the session.

// app/routes.php
Route::get('lang/{lang}', function($lang)
{
    Session::put('my.locale', $lang);
    return Redirect::to('/');
});

// app/start/global.php
App::setLocale(Session::get('my.locale', Config::get('app.locale')));
like image 76
Phill Sparks Avatar answered Oct 12 '22 12:10

Phill Sparks