【问题标题】:Localization issue in laravel applicationlaravel 应用程序中的本地化问题
【发布时间】:2020-09-15 05:00:49
【问题描述】:

我有两个域指向一个 laravel 应用程序。

test_en.site
test_fr.site

我的要求

test_en.site需要默认加载英文内容,test_fr.site需要加载法文内容。

(如果用户访问test_en.site,用户仍然可以将语言更改为法语,如果用户访问test_fr.site,用户可以将语言更改为英文。)

到目前为止我做了什么

为了检查域并相应地加载正确的语言,在我的中间件Localization.php中添加了以下条件。

app/Http/Middleware/Localization.php

<?php

namespace App\Http\Middleware;

use App;
use Closure;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
            return $next($request);
        }

        // load english by default if the root is test_en.site or else load french for other domains
        else {
            $locale = $request->root() == 'http://test_en.site' ? 'En' : 'Fr';
            App::setLocale($locale);
            return $next($request);
        }
    }
}

问题

我为具有两个测试域的同一个项目创建了两个虚拟主机,并在我的本地进行了尝试,然后它运行良好...

但是当我在实时服务器上对此进行测试时,它也会继续为法语域加载英语。

$locale = $request->root() == 'http://test_en.site' ? 'En' : 'Fr';
App::setLocale($locale);
return $next($request)

我什至尝试使用getHost() 方法而不是root(),但这也只适用于本地服务器...

我在哪里做错了,我该如何解决这个问题,因为这段代码在本地运行良好,我正在努力寻找解决方案......

【问题讨论】:

  • 可能更容易使用子域,因为它具有 Laravel 的内置支持。这样您就可以改用http://en.test.sitehttp://fr.test.site。然后在 Laravel 中,你可以简单地使用子域路由。这对您的应用程序是否可行?
  • @Qirel 感谢您的评论,但要求是使用两个不同的域......并且代码在本地服务器上运行良好......

标签: php laravel localization localhost laravel-6


【解决方案1】:

你的代码是正确的,我想你忘了把它添加到 Kernel.php 中

如果还是不行

试试这个 sn-p

p/s 已编辑


        // get subdomain
        $url_array = explode('.', parse_url($request->url(), PHP_URL_HOST));
        $subdomain = $url_array[0]; // in your case it should be test_en/test_fr

        $languages = ['test_en' => 'en', 'test_fr' => 'fr'];

        App::setLocale($languages[$subdomain]);

        return $next($request);

【讨论】:

  • 不,我已经把它加到内核中了,\App\Http\Middleware\Localization::class,对不起,我看不懂你的代码,请你解释一下跨度>
【解决方案2】:

您可以尝试使用https://github.com/movemoveapp/laravel-localization 本地化包。你的问题在这里描述https://github.com/movemoveapp/laravel-localization#localization-switch-by-domain-names

如何使用? 在您的情况下,您有:

  • test_en.site - 英文版
  • test_fr.site - 法语版本

安装包并添加到.env文件新环境


LOCALIZATION_DOMAIN_NAME_EN=test_en.site
LOCALIZATION_DOMAIN_NAME_FR=test_fr.site

下一步修改routes/web.php中的网络路由,比如

Route::group([
    'middleware' => [ 'localizationDomainRedirect' ]
], function()
{
    Route::get('/', function()
    {
        return View::make('index');
    });
});

所以,由 http://test_en.site/ 打开 En 版本,由 http://test_fr.site - Fr.

【讨论】:

  • @Steve 已修复。查看修改后的评论。
猜你喜欢
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
相关资源
最近更新 更多