使用Laravel 5.2并使用中间件,我需要在调度之前从请求的URI中删除某个部分。更具体地说,在像#34; 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
答案 0 :(得分:0)
我不认为第8行正在操纵你的输出
以下是laravel's code的path()
方法:
public function path()
{
$pattern = trim($this->getPathInfo(), '/');
return $pattern == '' ? '/' : $pattern;
}
正如您所看到的,它只是在不编辑请求本身的情况下提取pathInfo
。