Laravel 5 multi language site with language prefix in the url

廉价感情. 提交于 2019-12-30 07:21:14

问题


So I need multiple languages on a site with urls like this:

mysite/en/language
mysite/it/language
mysite/es/language

I decided to go with the prefix in my routes like so:

$allLanguages = ["en", "it", "es"];

$lng = ( in_array( Request::segment(1), $allLanguages) ) ? Request::segment(1) : "";

Route::group(['prefix' => $lng ], function () {
    Route::get('language', function ()    {
        dd("The language is: " . Request::segment(1));
    });
});

It works, but if I wanted to set up a default language and access url like so mysite/language - it wouldn't work.

What are your thoughts? Is this the best way how to handle multi language site? How to address the problem when accessing site without prefix ( show page with default language )?


回答1:


After some research I found this beautiful localization class mcamara/laravel-localization. After installation my code now looks like this and it's all working - magic!!

Route::group(['prefix' => LaravelLocalization::setLocale() ], function () {
    Route::get('language', function ()    {
        dd("The language is: " . LaravelLocalization::getCurrentLocale());
    });
});


来源:https://stackoverflow.com/questions/35573932/laravel-5-multi-language-site-with-language-prefix-in-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!