2

How can I get all routes in project which have GET method? I have tried:

Route::getRoutes() which gave me all routes but somehow I could not have filtered them by method.

The Route::getRoutes()->routes would be nice to have but routes is protected property and I do not see any getter.

Epsilon47
  • 768
  • 1
  • 13
  • 28
  • what does `Route::getRoutes()` give you? could you not filter that result into only get? Apparently it gives you back an array so you could run it through `array_filter` to get only the ones you want – Dale Sep 05 '18 at 08:55
  • I get a collection: ` RouteCollection {#28 ▼ #routes: array:7 [▼ "GET" => array:124 [▶] "HEAD" => array:124 [▶] "POST" => array:63 [▶] "PUT" => array:1 [▶] "PATCH" => array:1 [▶] "DELETE" => array:21 [▶] "OPTIONS" => array:1 [▶] ] ... from which I would like to get only GET routes – Epsilon47 Sep 05 '18 at 08:57
  • in that case maybe `Route::getRoutes()['GET']` it's a little hard to read in your comment – Dale Sep 05 '18 at 08:58
  • There is also getRouteByMethod() see this api page https://laravel.com/api/5.6/Illuminate/Routing/RouteCollection.html#method_getRoutes – Dale Sep 05 '18 at 09:00
  • Couldn't you do the same as what's done in [this answer](https://stackoverflow.com/a/18395300/5283119). Get all routes, loop over them and create your own array? –  Sep 05 '18 at 09:41

2 Answers2

3

you can create small helper method.

function getRoutesByMethod(string $method){
    $routes = \Route::getRoutes()->getRoutesByMethod();
    return $routes[$method];
}

then use it in your application

$postRoutes = getRoutesByMethod("POST");
Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41
2

The RouteCollection has a method to sort the routes by their method(eg. GET).

You can use it as below to get the GET routes:

Route::getRoutes()->getRoutesByMethod()['GET']

And to get POST routes:

Route::getRoutes()->getRoutesByMethod()['POST']
larsemil
  • 880
  • 9
  • 15