How to list routes in Laravel (No Artisan)?

Asked

Viewed 2,281 times

1

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

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

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

Can you do that? I would like an answer that would work so hard on Laravel 4 and in the Laravel 5.

  • 1

    http://stackoverflow.com/a/23673413/5165064 take a look at

2 answers

2


Wallace, you can do it this way:

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

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

So if you look in 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 be confused with Router) that you added to Laravel.

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

Thus:

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

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

Thus:

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

1

Complementing the reply of the friend above follows the code:

Filing cabinet /Routes/web.php

Route::get('/rotas', 'TesteController@index');

Filing cabinet /app/Http/Controlers/Testecontroller.php

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

Filing cabinet /Resources/views/routes.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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.