How to list the routes in Laravel (Without using artisan)?

1

No Laravel 4 I know how to list all routes through the command line. Just do php artisan routes .

But now, I have to do this in the source code of my application.

That is, I need to list the routes (in foreach for example), capturing their names.

Can you do this? I would like a response that works both in Laravel 4 and Laravel 5 .

    
asked by anonymous 17.02.2016 / 12:03

2 answers

1

Wallace, you can do as follows:

foreach (Route::getRoutes() as $route) {
    var_dump($route->getUri());
}

The class Route is a facade for class Illuminate\Routing\Router in Laravel .

So if you look at this class, it has a method called Router::getRoutes . This method will return an instance of Illuminate\Routting\RouteCollection , which is a collection of routes ( Illuminate\Routing\Route not to confuse with Router ) that you added in Laravel .

If you want to transform the object of class RouteCollection to array , just call the method getRoutes again (however this time is RouteCollection and not Router ).

So:

var_dump(Route::getRoutes()->getRoutes());

You can also capture the route name using the Illuminate\Routing\Route::getName() method.

So:

foreach (Route::getRoutes() as $route) {
    var_dump($route->getName());
}
    
17.02.2016 / 12:24
0

Complementing the friend response above follows the code:

File /routes/web.php

Route::get('/rotas', '[email protected]');

File /app/Http/Controlers/TestController.php

public function index()
{
    return view("rotas", [
       'resource' => Route::getRoutes()->getRoutes()
    ]);
}

File /resources/views/rotas.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <title>Rotas API</title>
</head>
<body>
<div class="container">
    <table class="table table-striped">
        <thead>
        <tr>
            <td>URL</td>
            <td>MÉTHODO</td>
        </tr>
        </thead>
        <tbody>
        @foreach($resource as $rs)
            <tr>
                <td>{{$rs->uri}}</td>
                <td>{{$rs->methods[0]}}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>
</body>
</html>
    
19.05.2018 / 02:43