I'm trying to implement a laravel website that supports two languages (pt and en with pt fallback already implemented). The desired url's should be www.example.com/pt/list for portuguese and www.example.com/en/list for english. When no language is inserted, should work with pt for default. I have the following code: [routes.php]
Route::filter('localization', function() {
App::setLocale(Route::input('lang'));
});
Route::group(['prefix' => '{lang?}', 'before' => 'localization'], function() {
Route::get('/', 'HomeController@index');
Route::get('/list','ListController@index');
});
When language is defined all works well, but otherwise it will always redirect to the homepage even when there is no router to this URL. How can I avoid this behaviour? Is it possible to do a regex on a group? Guess the Jason Lewis' Enhanced Router only works in Laravel 4
EDIT 1: I could fix it using redirects in htaccess (if no language prefix, then redirect using /pt/ prefix but there must be another way I guess)
EDIT 2: Can fix it using the following piece of code but it also involves using redirects, which I guess it could be prevented and the url will always have the language parameter
Route::filter('localization', function() {
$accepted_language = array("pt","en");
$first_segment = Route::input("lang");
if(in_array($first_segment,$accepted_language))
{
/*ALL GOOD, Language in URL*/
App::setLocale(Route::input('lang'));
}
else
{
/*REDIRECT WITH LANGUAGE*/
$segments = Request::segments();
$imploded = implode("/",$segments);
$url = "/pt/".$imploded;
return Redirect::to($url, 301);
}
});
In my recent project I had the same problem. You can do it like this:
$languages = array('en', 'pt');
$locale = Request::segment(1);
if (in_array($locale, $languages))
{
App::setLocale($locale);
}
else
{
redirect('pt')->send();
}
Route::group(['prefix' => $locale], function()
{
Route::get('/', 'HomeController@index');
Route::get('list','ListController@index');
});
Or move locales check into the separate middleware.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.