Creating Multilingual Translated Routes in Laravel
This guide provides a comprehensive solution for creating multilingual translated routes in Laravel, ensuring that the current language is determined solely by the URL, rather than relying on cookies or sessions.
Implementation:
1. Translation Files:
Create translation files for the desired routes in the app/lang/[LANGUAGE]/routes.php directory. For example, for Polish (pl), English (en), and French (fr):
app/lang/pl/routes.php:
return array( 'contact' => 'kontakt', 'about' => 'o-nas' );
app/lang/en/routes.php:
return array( 'contact' => 'contact', 'about' => 'about-us' );
2. Configuration:
Update app/config/app.php:
Set the default language (e.g., Polish):
'locale' => 'pl',
List the alternative languages (English and French):
'alt_langs' => array ('en', 'fr'),
Define the locale prefix:
'locale_prefix' => '', // Will be dynamically updated at runtime
3. Routes:
Edit app/routes.php:
... // Set locale and locale_prefix if an alternative language is selected if (in_array(Request::segment(1), Config::get('app.alt_langs'))) { App::setLocale(Request::segment(1)); Config::set('app.locale_prefix', Request::segment(1)); } // Set route patterns based on the translated routes foreach(Lang::get('routes') as $k => $v) { Route::pattern($k, $v); } Route::group(array('prefix' => Config::get('app.locale_prefix')), function() { Route::get( '/', function () { return "main page - ".App::getLocale(); } ); Route::get( '/{contact}/', function () { return "contact page ".App::getLocale(); } ); Route::get( '/{about}/', function () { return "about page ".App::getLocale(); } ); }); ...
This configuration dynamically updates the locale and locale prefix based on the first URL segment (if it matches an alternative language) and sets route patterns according to the translated routes.
4. Redirection (Optional):
For unknown URLs, redirect to the current language prefix (e.g., /en) instead of the default language (/):
// app/start/global.php App::missing(function() { return Redirect::to(Config::get('app.locale_prefix'),301); });
The above is the detailed content of How can I create multilingual, translated routes in Laravel without relying on cookies or sessions?. For more information, please follow other related articles on the PHP Chinese website!