Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set locale on the fly in laravel4

After searching through the documentation from laravel 4 I see that the way to set a language is to do

App::setLocale('en');

But how do I use this in combination with for example a language switcher on my website that a visitor can click on to change the language on the fly? and to remember this with a cookie or something?

It seems that in laravel 3 it was much easier but since im new to laravel I don't know how to figure this out so if someone knows what to do and can help me out it would be great :)

like image 530
Reshad Avatar asked Nov 28 '13 19:11

Reshad


2 Answers

This is a way:

Create a route for your language selector:

Route::get('language/{lang}', 
           array(
                  'as' => 'language.select', 
                  'uses' => 'LanguageController@select'
                 )
          );

Create your language selectors links in Laravel Blade's view:

<html><body>

    Please select a Language:

    {{link_to_route('language.select', 'English', array('en'))}}

    {{link_to_route('language.select', 'Portuguese', array('pt'))}}

</body></html>

A Controller:

Class LanguageController extends BaseController {

    public function select($lang)
    {
        Session::put('lang', $lang);

        return Redirect::route('home');
    }

}

Then in your app/start/global.php you can:

App::setLocale(Session::get('lang', 'en'));
like image 168
Antonio Carlos Ribeiro Avatar answered Nov 05 '22 23:11

Antonio Carlos Ribeiro


There is great library for Laravel that allows you to handle locales flexible - mcamara laravel localization. In readme of the project you can find example how to implement such a switcher.

like image 38
qbasso Avatar answered Nov 06 '22 00:11

qbasso