Home > Enterprise >  How do Laravel route groups work under the hood?
How do Laravel route groups work under the hood?

Time:11-01

I was wondering how is this working under the hood:

Route::group(['prefix' => 'parent'], function() {
    Route::get('/child', 'MyController@myMethod');
});

I don't understand how is Laravel associating the routes definitions in the anonymous function to the parent group.

Something like this would have made much more sense:

Route::group(['prefix' => 'parent'], function($group) {
    $group->get('/child', 'MyController@myMethod');
});

I tried diving into what happens under the hood through a debugger, and I noticed that in Illuminate\Routing\Router.php this happens:

protected function loadRoutes($routes)
{
    if ($routes instanceof Closure) {
        $routes($this);
    } else {
        (new RouteFileRegistrar($this))->register($routes);
    }
}

The anonymous function that contains our routes definitions is called and $this gets passed to it, altho our anonymous function doesn't accept any argument, so why passing $this to it?

CodePudding user response:

Route groups are a concept and they are used for cascading configuration. The way Laravel knows what configuration to apply to the routes in a "group" is because it keeps a stack of all the groups that are open so it can apply to the routes. You could just load a route file into the group which doesn't involve any closures.

Since there is a stack of the current configuration any route definition at that point will have that configuration. Before the group call finishes executing it pops the current configuration off of the stack (which conceptually closes the group since that configuration doesn't exist on the stack any longer so it won't be applied to any further defined routes).

Any call to define a route at any time will check to see if there is a group stack and cascade the configuration and apply it if needed. You could add information to the group stack yourself without calling group and then every route you define after that will have that configuration regardless of if it was defined in a route group or not.

The comment from the group method of Illuminate\Routing\Router:

Once we have updated the group stack, we'll load the provided routes and merge in the group's attributes when the routes are created. After we have created the routes, we will pop the attributes off the stack.

  • Related