laravel的本地化

问题描述 投票:1回答:2

我用Laravel设计了一个网站。现在我想为它添加新语言。我读了laravel document。这很好,但我有一个问题。假设我有一个页面显示产品的细节,所以我有一个像mysite.com/product/id的路线,获得产品的ID并显示它。我也有一个方法在控制器像

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

如果我添加新语言,路由将更改为:mysite / en / product / id现在我必须更改我的方法,因为现在两个参数发送我的method.something如下:

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

因此出现两个问题:

  1. 我必须在我的网站中更改所有方法,这非常耗时
  2. 我不需要方法中的语言参数因为我通过中间件设置$ locan注意我不想从我的URL中删除例如en(因为SEO)
laravel localization
2个回答
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())));

}

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


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...
});
© www.soinside.com 2019 - 2024. All rights reserved.