Laravel 5多语言站点,URL中带有语言前缀 [英] Laravel 5 multi language site with language prefix in the url

查看:370
本文介绍了Laravel 5多语言站点,URL中带有语言前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在网站上需要多种语言,并具有以下网址:

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));
    });
});

它可以工作,但是如果我想设置默认语言并像 mysite/language 这样访问url-则行不通.

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 )?

推荐答案

经过研究,我发现了这个漂亮的本地化类

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());
    });
});

这篇关于Laravel 5多语言站点,URL中带有语言前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆