douhan1860 2016-08-05 11:33
浏览 250

Laravel 5 - 在中间件中调用$ request-> path()导致Laravel忽略对请求URI的更改?

Using Laravel 5.2, and using a middleware, I need to remove a certain part from the URI of the request before it gets dispatched. More specifically, in a url like "http://somewebsite.com/en/company/about", I want to remove the "/en/" part from it.

This is the way I am doing it:

...

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

This code is working fine - when the original URI is "en/company/about", the resulting URI is indeed "company/about". My issue is this: notice that the line where I echo the ORIGINAL PATH is commented (line 8). This is done on purpose. If I uncomment this line, the code is not working; when the original URI is "en/company/about", the resulting URI is still "en/company/about".

I can only reach two conclusions from this: Either sending output before manipulating the request is somehow the culprit (tested - this is not the case), or calling the $request->path() method to get the URI has something to do with this. Although in production I will never need to echo the URI of course, and while this is only for debugging purposes, I still need to know why this is happening. I only want to get the URI of the request. What am I missing here?

Sidenote: The code originated from the first answer to this post: https://laracasts.com/discuss/channels/general-discussion/l5-whats-the-proper-way-to-create-new-request-in-middleware?page=1

  • 写回答

1条回答 默认 最新

  • dongzongxun8491 2016-08-05 14:03
    关注

    I don't think that line#8 is manipulating your output.
    Here is the path() method from laravel's code:

    public function path()
        {
            $pattern = trim($this->getPathInfo(), '/');
            return $pattern == '' ? '/' : $pattern;
        }
    

    As you can see it is just extracting the pathInfo without editing the request itself.

    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上