0

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

pazof
  • 944
  • 1
  • 12
  • 26

1 Answers1

1

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.

jaysingkar
  • 4,315
  • 1
  • 18
  • 26
  • I know, that's why this seems so awkward to me. How can it be then, that the code works perfectly when that line is commented, but doesn't work when it isn't? – pazof Aug 05 '16 at 14:28
  • I will try to do the same with my setup and will let you know – jaysingkar Aug 05 '16 at 15:12