Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

realtebo's avatar

How to 'compose' the route definitions?

I have this main group

Route::group([
    'prefix' => 'backend',
    'middleware' => ['web']
], function () {
...

Inside it, I've this subgroup

Route::group([
        'middleware' => ['auth']
    ], function () {

With another subgroup

Route::group([
            'namespace' => 'Users',
            'prefix' => '',
        ], function(){

And inside this I've a tons of routes. I'd like to splite route definitions in a few files and the 'compose' the final route files.

I'd like to avoid brutal require (...).

Is there a way to load some routes from a file/class/helper/whatelse and 'inject' in the final file in the appropriate row? Like a blade has inclusion methods, ... something similar

0 likes
1 reply
papa's avatar

@realtebo

One think that you can do in web.php file is this

foreach(File::allFiles(__DIR__.'/web') as $file) {
    require $file->getPathname();
}

where in web folder you have multiple files of routes

A second option is to add some code in RouteServiceProvider

as an example

protected function mapModuleRoutes()
    {
        foreach ($this->modules as $module) {
            if (file_exists(app_path('Modules/' . $module .'/routes.php'))) {
                Route::middleware('web')
                    ->namespace($this->namespace)
                    ->group(app_path('Modules/'. $module . '/routes.php'));
            }
        }
    }

Here I have modular structure and each module has its routes.php file

1 like

Please or to participate in this conversation.