Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Parse arbitrary URL to its corresponding Controller/Route?

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.

like image 461
Tim Schmidt Avatar asked Sep 27 '22 15:09

Tim Schmidt


1 Answers

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.

like image 77
Bogdan Avatar answered Sep 29 '22 19:09

Bogdan