【问题标题】:Localization in laravellaravel 本地化
【发布时间】:2018-09-15 21:09:35
【问题描述】:

我用 Laravel 设计了一个网站。现在我想为它添加新语言。我读了laravel document。这很好,但我有一个问题。假设我有一个显示产品详细信息的页面,所以我有一个像 mysite.com/product/id 这样的路由来获取产品的 id 并显示它。我在控制器中有一个方法,比如

public function showProduct($id){
  ...
}

如果我添加新 Language ,路线将更改为:mysite/en/product/id 现在我必须改变我的方法,因为现在有两个参数发送我的方法。像这样:

public function showProduct($lang,$id){
  ...
}

于是出现了两个问题:

  1. 我必须更改网站中的所有方法,这很耗时
  2. 我不需要方法中的语言参数,因为我通过中间件设置了 $locan 请注意,我不想从我的 URL 中删除例如 en(因为 SEO)

【问题讨论】:

  • 或许可以通过显式注册您支持的语言路由来解决这个问题?

标签: laravel localization


【解决方案1】:

打开你的RouteServiceProvider 并说语言参数实际上不是参数,它是一个全局前缀。

protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
        'prefix' => Request::segment(1) // but also you need a middleware about that for making controls..
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

这里是示例语言中间件,但需要改进

public function handle($request, Closure $next)
{
    $langSegment = $request->segment(1);
    // no need for admin side right ?
    if ($langSegment === "admin")
        return $next($request);
    // if it's home page, get language but if it's not supported, then fallback locale gonna run
    if (is_null($langSegment)) {
        app()->setLocale($request->getPreferredLanguage((config("app.locales"))));
        return $next($request);
    }
    // if first segment is language parameter then go on
    if (strlen($langSegment) == 2)
        return $next($request);
    else
    // if it's not, then you may want to add locale language parameter or you may want to abort 404    
        return redirect(url(config("app.locale") . "/" . implode($request->segments())));

}

所以在你的控制器中,或者在你的路由中。你没有处理语言参数

【讨论】:

    【解决方案2】:

    有点像

    Route::group(['prefix' => 'en'], function () {
        App::setLocale('en');
        //Same routes pointing to the same methods...
    });
    

    或者

    Route::group(['prefix' => 'en', 'middleware' => 'yourMiddleware'], function () {
        //Same routes pointing to the same methods...
    });
    

    【讨论】:

    • 谢谢,但我对更改路线没有问题。本地化后,新参数发送我的所有功能,所以我必须更改所有这些很无聊。我搜索新参数(敌人示例:fa)不传递给方法的解决方案
    • 我认为你要么对你的路线做一些改变,要么做你不想做的事情。看到这个非常相似的问题。 stackoverflow.com/questions/24789577/…
    猜你喜欢
    • 2018-07-14
    • 2019-08-29
    • 2021-04-03
    • 2014-06-26
    • 1970-01-01
    • 2019-02-25
    • 2018-12-08
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多