Flash-Square
Flash-Square

Reputation: 441

laravel 4 multilanguage website

I'm trying to implement a multilanguage laravel 4 website, with language code in the url ( mywebsite.com/en/home and mywebsite.com/de/home )

I've seen a couple of options like filtering all requests and checking if the first param is one of the language code.

I've also check on packagist but haven't find something that already do tee job.

Is there a better way to implement it?

Thank you

Upvotes: 3

Views: 5779

Answers (2)

Flash-Square
Flash-Square

Reputation: 441

Finally, I've create a config variable in config/app.php

'available_language' => array('en', 'fr', 'es'),

In filters.php I detect the browser language:

Route::filter('detectLang', function($lang = "auto")
{
    if($lang != "auto" && in_array($lang , Config::get('app.available_language')))
    {
        Config::set('app.locale', $lang);
    }else{
        $browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
        $browser_lang = substr($browser_lang, 0,2);
        $userLang = (in_array($browser_lang, Config::get('app.available_language'))) ? $browser_lang : Config::get('app.locale');
        Config::set('app.locale', $userLang);
    }
});

and then in routes.php I can either detect the language or force it:

Route::get('/', array(
    'before' => 'detectLang()', // auto-detect language
    function(){
        ...
    })
);

or

Route::get('/', array(
    'before' => 'detectLang("fr")', // force language to "fe"
    function(){
        ...
    })
);

Upvotes: 6

Laurence
Laurence

Reputation: 60048

You could set a language variable in the user session.

Then use a 'before' filter, and view that variable, and log the correct language file.

If there is no variable set - then use a default (perhaps based upon their IP location).

Upvotes: 0

Related Questions