Given I have an arbitrary URL mapped (amongst many others) like this
...
Route::get('/foobar/{parameter}', 'MyFoobarController@index');
...
How can I "reverse parse/resolve" the URL (like http://localhost/foobar/foo
) into this configured controller (MyFoobarController
) again? Please note: I am not talking about the current Request but a general approach to parse any URL that is mapped in Laravel to its corresponding Controller and Action (anywhere in the code independent of the current request). Thanks!
Update: It should also correctly match Routes, that have parameters in them.
You can compare the URL path, to the paths added to the router. So let's take your example:
Route::get('/foobar', 'MyFoobarController@index');
You can use the Route
facade to get a list of all registered routes:
// This is your URL as a string
$url = 'http://localhost/foobar';
// Extract the path from that URL
$path = trim(parse_url($url, PHP_URL_PATH), '/');
// Iterate over the routes until you find a match
foreach (Route::getRoutes() as $route) {
if ($route->getPath() == $path) {
// Access the action with $route->getAction()
break;
}
}
The getAction
method will return an array containing the relevant information about the action mapped for that route. You can check out the Illuminate\Routing\Route
API for more info on what methods are available for you to use once you have matched a route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With