skip to Main Content

Laravel site root is https://example.com/path_to_root/

To get to what would be URL path / in a normal site, you actually go to https://example.com/path_to_root/

So, the Laravel site is under /path_to_root/ and there is other non-Laravel content in for, example,
https://example.com/other

How do I get the portion of the URL path that consists of / all the way up to the base of all of the Laravel content? In this case, it would be /path_to_root

Another example: if my site was based totally under https://example.com/my/news
Then it would be /my/news. In that case, the entirity of the Laravel site would be under /my/news and if I defined a path in Laravel called / then the URL path would actually be /my/news. In that case, i would want the function to return /my/news. That’s what I refer to as the URL path to root and I don’t know how to get that programmatically.

Also note that the user could be under any page of the site. For example they could be requesting https://example.com/my/news/a/z/?x=1

I’m not referring to the file system path.

2

Answers


  1. Chosen as BEST ANSWER

    This seems to work:

    //...
    
    public static function requestPath()
    {
    
        // save url to return to in request parameter
        $thisPath = Request::getRequestUri();
    
        // figure out URL path to root so we can subtract it from
        // Path to page to redirect to or Laravel won't redirect right.
        // This is for dev sites that may be under a path instead of
        // beling located at /
    
        $rootURL = URL::to('/');
    
        $rootPath = parse_url($rootURL, PHP_URL_PATH);
    
        if (strlen($rootPath) > 1 
            && substr($thisPath, 0, strlen($rootPath)) == $rootPath)
        {
            // Laravel expects paths to start at URL site root (???)
            $thisPath = substr($thisPath, strlen($rootPath));
        }
    
    
        return $thisPath;
    }
    

  2. From my understanding of the question, what you need is request()->path().

    Given https://example.com/path_to_root/ it would return path_to_root.

    '/'.request()->path().'/' would give /path_to_root/.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search