我与Laravel设计了一个站点。现在我想为其添加新语言。我读了laravel document。很好,但是我有一个问题。假设我有一个页面来显示产品的详细信息,所以我有一条路线,例如mysite.com/product/id,它获取并显示了产品的ID。此外,我在控制器中也有一种方法,例如>
INT
如果添加新的Language,则路由将更改为此:mysite / en / product / id 现在我必须更改我的方法,因为现在有两个参数发送我的方法。类似这样:
public function showProduct($id){
...
}
因此出现两个问题:
答案 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...
});