laravel本地化

时间:2018-08-18 05:05:18

标签: laravel localization

我与Laravel设计了一个站点。现在我想为其添加新语言。我读了laravel document。很好,但是我有一个问题。假设我有一个页面来显示产品的详细信息,所以我有一条路线,例如mysite.com/product/id,它获取并显示了产品的ID。此外,我在控制器中也有一种方法,例如

INT

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

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

因此出现两个问题:

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

2 个答案:

答案 0 :(得分: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())));

}

因此在您的控制器或您的路线中。你没有处理语言参数

答案 1 :(得分:0)

类似

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