Search code examples
phplaravellaravel-5routesassets

Laravel 5.1 - get current route


I'm working on a function to get assets (.css, .js) automatically for each view. So it works fine for let's say, "http://mywebsite.com/displayitems", /home, /about etc.

But since I wrote the function using $_SERVER['REQUEST_URI'], I came up with an issue when I had a route like /displayitems/1 because of the "/1" in the route.

Back then in Laravel 4.x I had a great way to do it but sadly it doesn't work the same way in Laravel 5.4.

I've been searching through the internet for a good method to get the current route but no success. The thing is that I have to ignore any parameters in the request URL.

If anyone has a clue, or maybe am I doing it wrong and there's a completely different, better way to do it?

P.S My current function:

public static function getAllRouteAssets() {
    $route = $_SERVER['REQUEST_URI'];
    if($route == "/") {
        $tag = '<link href="' . asset("assets/css/pages/home.css") . '" rel="stylesheet" type="text/css"/>';
    }
    else {
        // CSS
        $tag = '<link href="' . asset("assets/css/pages" . $route . ".css") . '" rel="stylesheet" type="text/css"/>';
    }
    echo $tag;

    //TODO: Check if file exists, homepage condition, js...
}

Solution

  • You may try this:

    // Add the following (`use Illuminate\Http\Request`) statement at top your the class
    
    public static function getAllRouteAssets(Request $request)
    {
        // Get the current route
        $currentRoute = $request->route();
    }
    

    Update (Get the Request instance from IoC/Service container and call route() to get current route):

    app('request')->route(); // Current route has been retrieved
    

    If you want to pass the current route as a parameter to your getAllRouteAssets method then you have to change the typehint or pass the Request and call the route method from within the getAllRouteAssets method.