skip to Main Content

I have been working on a Laravel project where I needed to organize my codebase using modules. To achieve this, I created separate directories for each module under the app/Modules folder. One challenge I faced was generating routes automatically for each module without explicitly defining them.

After some research and experimentation, I came up with the following approach:

    if (File::isDirectory(MODULE_PATH)) {
        $moduleDirectories = File::directories(MODULE_PATH);
            foreach ($moduleDirectories as $directory){
              $module = basename($directory);
                Route::prefix(lcfirst($module))->group(function () use ($module) {
                  require_once app_path("Modules/{$module}/Routes/api.php");
                });
            }
    }

In this approach, I check if the MODULE_PATH directory exists (which points to the app/Modules folder). If it does, I iterate through each module directory. For each module, I extract the module name using basename($directory) and set it as the route prefix using Route::prefix(lcfirst($module)).

Inside the route group, I include the module’s API routes by requiring the api.php file located in the module’s directory. This allows me to define module-specific routes in separate files, keeping the codebase clean and organized.

Now, my application automatically generates routes for each module based on the module directories present in the app/Modules folder.

I would like to know if this approach is considered a good practice in Laravel development. Are there any potential drawbacks or better alternatives for achieving automatic module-based route generation using directories?

I appreciate any insights or suggestions from the Laravel community. Thank you!

2

Answers


  1. it is good way to generating routes dynamically based on modules ,
    but keep in mind some things

    1. module names they must be unique
      2)if modules increases , it may imapact on Performance , like generating every time new routes , then it will looping the directories , check if exists etc

    If you prefer , you can use below alternative
    define routes inside root directories web/api

    Route::prefix('firstmodule')->group(function () {
        //  firstmodule routes
        Route::get('/', 'AppModulesFirstmoduleControllersOneController@index');
    });
    
    Route::prefix('secondmodule')->group(function () {
        // secondmodule route
        Route::get('/', 'AppModulesSecondmoduleControllersTwoController@index');
    });
    
    Login or Signup to reply.
  2. Can this routes be cached?

    The "correct" Laravel way would be for each module to define it’s RouteServiceProvider with it’s own prefix and load the routes from there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search