使用 Laravel 5.2 并使用中间件,我需要从请求的 URI 中删除某个部分,然后再分派它。更具体地说,在像“ http://somewebsite.com/en/company/about ”这样的网址中,我想从中删除“/en/”部分。
这就是我这样做的方式:
...
class LanguageMiddleware
{
public function handle($request, Closure $next)
{
//echo("ORIGINAL PATH: " . $request->path()); //notice this line
//duplicate the request
$dupRequest = $request->duplicate();
//get the language part
$lang = $dupRequest->segment(1);
//set the lang in the session
$_SESSION['lang'] = $lang;
//now remove the language part from the URI
$newpath = str_replace($lang, '', $dupRequest->path());
//set the new URI
$request->server->set('REQUEST_URI', $newpath);
echo("FINAL PATH: " . $request->path());
echo("LANGUAGE: " . $lang);
$response = $next($request);
return $response;
}//end function
}//end class
此代码运行良好 - 当原始 URI 为“en/company/about”时,生成的 URI 确实为“company/about”。我的问题是这样的:请注意,我回显 ORIGINAL PATH 的行已被注释(第 8 行)。这是故意的。如果我取消注释此行,则代码不起作用;当原始 URI 是“en/company/about”时,生成的 URI 仍然是“en/company/about”。
我只能由此得出两个结论:要么在操作请求之前发送输出是罪魁祸首(经过测试 - 事实并非如此),要么调用 $request->path() 方法来获取 URI 与这个。虽然在生产中我当然不需要回显 URI,虽然这仅用于调试目的,但我仍然需要知道为什么会发生这种情况。我只想获取请求的 URI。我在这里想念什么?
旁注:代码源自这篇文章的第一个答案: https ://laracasts.com/discuss/channels/general-discussion/l5-whats-the-proper-way-to-create-new-request-in-middleware ?page=1