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...
}
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.
I know this is a bit old, but there is a method that gives you the entire query path:
$request->getPathInfo();
However, note that this will not work if you are looking to fetch the query string as well. (FYI, Laravel 5 does not support query strings by default)
You can individually fetch the GET variables from the query strings by:
$request->input('id');
Example:
http://laravel.com/api/users/?id=123
would return /api/users
using getPathInfo()
and 123
using $request->input('id');
I am using Laravel 5.5.20. I had also need to get part of route without get parameters. Routes are defined without question mark(?) in web.php, as for example:
Route::get('board/{param_1}/{param_2}', 'BoardController@index');
In that case I did not see direct method in Route class to get part without url parameters.
Here is how I got static part (/board):
...
use Illuminate\Support\Facades\Route;
..
$staticPrefix = Route::getCurrentRequest()->route()->getCompiled()->getStaticPrefix();
...