Search code examples
laravelroutesappcontainer

Register route using app container Laravel


I would like to register my routes (endpoints) dynamically in Laravel. I am not using routes.php, yet I want to register routes using

$this->app->get()

or similiar, in service provider. Furthermore I would like also to add a middleware this way to dynamically registered route.


Solution

  • You can take a look at your RouteServiceProvider@map in App\Providers to see how Laravel imports the routes.php file.

    You can then import your JSON file convert it to an array and loop through it.

    Your JSON file can look like this

    [
        {
            "method": "get",
            "uri": "/profile",
            "action": {
                "as": "profile",
                "uses": "UserController@showProfile",
                "middleware": "auth"
            }
        }
    ]
    

    When you decode this you can then do something like that

    \Route::$method($uri, $action);