Reputation: 89
I have a yii site ti be transformed to laravel any help to apply the **laravel localization ** to the url such as
localhost/en/home localhost/ar/home
Upvotes: 1
Views: 1611
Reputation: 89
the answer of Denis Mysenko is amazingly working and in the view to add a dynamic urls and a language switcher here is the code
<div class="language_switcher">
<ul>
<li><a href="{{ url('/en') }}">en</a></li>
<li><a href="{{ url('/ar') }}">ar</a></li>
</ul>
</div>
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<center>
<div class="navbar-collapse collapse" id="navbar-main">
<div class="clearfix"></div>
<div class="clearfix"></div>
<ul class="nav navbar-nav navbar-right">
<li><a href="{{ url('/' ,$language) }}">HOME</a></li>
<li><a href="{{ url('/ABOUT-US' , $language) }}">ABOUT US</a></li>
<li><a href="{{ url('/HOW-IT-WORKS' ,$language) }}">HOW IT WORKS</a></li>
<li><a href="{{ url('/CONTACT-US' ,$language) }}">CONTACT US</a></li>
</ul>
</div>
</center>
Upvotes: 0
Reputation: 6534
This is very simple to do in Laravel. First, you need to add a language prefix in your routes file (routes.php):
$languagesRegExp = implode('|', array_keys(Config::get('app.languages')));
Route::pattern('language', $languagesRegExp);
This will be our language prefix - it will only allow items from the languages[] specified in our app config file (config/app.php):
'languages' => [
'ru' => ['prefix' => 'ru', 'title' => 'По-русски', 'locale' => 'ru_RU.utf8', 'google_code' => 'ru'],
'en' => ['prefix' => 'en', 'title' => 'English', 'locale' => 'en_US.utf8', 'google_code' => 'en']
],
Then, routes that are going to have translated versions will look like:
Route::group(['middleware' => 'language'], function () {
Route::get('/{language}', 'IndexController@index');
Route::get('/{language}/about', 'StaticController@about');
}
Now we need a middleware because we want to change the application locale based on the prefix parameter. The middleware has a single method:
public function handle($request, Closure $next)
{
$urlSegments = explode('/', $request->path());
View::share('language', $urlSegments[0]); // All views will have $language variable now
App::setLocale($urlSegments[0]); // Laravel locale is set to $language now
Cookie::queue(Cookie::make('siteLanguage', $urlSegments[0], 10800 * 7)); // We can also set a cookie, so that language is remembered
return $next($request);
}
Pretty much that's it!
Upvotes: 1