How to get language switching back in Laravel 4
In Laravel 3, we could easily change from a language to another by prefixing the route URL with the language code (for example http://mysite.com/account/info becoming http://mysite.com/fr/account/info).
With Laravel 4, this feature is not available anymore. With that in mind, @jacekd on Github had the idea of adding a code to handle this feature in the App::before
filter. I optimized it using Laravel's core methods.
Here are the steps needed to get language switching back in Laravel 4:
-
add an
Array
containing the available languages in config/app.php'languages' => array('en', 'fr', 'de', 'es'),
-
add this code to filters.php
App::before(function($request) { if ( in_array(Request::segment(1), Config::get('app.languages')) ) { Session::put('locale', Request::segment(1)); return Redirect::to(substr(Request::path(), 3)); } if ( Session::has('locale') ) { App::setLocale(Session::get('locale')); } });
Written by Dhaya Benmessaoud
Related protips
4 Responses
Thanks for the info. This works well at switching the languages with sessions, but it doesn't keep the language code in the url. Maybe that's your aim, though. I don't know if it's better for SEO this way or with the language code.
Hi @aardvark2, you're guessing right. This is not perfect for SEO. Why did Laravel remove the useful path prefixing? I don't know. If you want to keep the language prefixing you could do something by tweaking the global before filter and adding a Route prefix, something like this: https://gist.github.com/dhayab/6172253.
Hello Dhaya,
Nice work here !
Have you any idea on how to "update" the URL helper to make it write the language prefix each time he is used ?
Regards !
Thanks for this. I made a few improvements so that URL in views are prefixed.
@romainsauvaire, take a look : https://coderwall.com/p/czumyq