lazerg/laravel-modular

There is no license information available for the latest version (v0.13) of this package.

Laravel Modular

v0.13 2024-07-05 01:47 UTC

This package is auto-updated.

Last update: 2025-01-05 03:16:31 UTC


README

cover

Version Downloads count Repository count Last commit Stars count

Dividing a Laravel project into modules enhances code organisation by isolating features and functionalities into separate, manageable units. This modular approach improves scalability by allowing each module to be developed, tested, and maintained independently, which speeds up development and reduces the risk of conflicts.

It also promotes reusability, as modules can be easily reused in other projects, fostering a more efficient development process and reducing duplication of effort.

Installation

composer require lazerg/laravel-modular

Create a new module

When we start a new project, we need to move current files to modules. Let's create modules/User/app directory. And register it in composer.json file.

{
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/",
            "Modules\\User\\": "modules/User/app/",
            "Modules\\User\\Database\\Factories\\": "modules/User/database/factories/",
            "Modules\\User\\Database\\Seeders\\": "modules/User/database/seeders/"
        }
    }
}

Do not forget to composer dump-autoload after changes.

After registering module, create UserServiceProvider in modules/User/app directory. It must extend ModuleServiceProvider. Next you need to register this service provider in bootstrap/providers.php file.

Move default files to module

  1. Move /app/Modules/User to /modules/User/app/Modes/User
  2. Change auth.providers.users.model config to Modules\User\Models\User.
  3. Move /database/migrations/2014_10_12_000000_create_users_table.php to /modules/User/database/migrations/2014_10_12_000000_create_users_table.php
  4. Move /database/factories/UserFactory.php to /modules/User/database/factories/UserFactory.php

Setup seeder

  1. database/seeders/DatabaseSeeder.php must extend ModularDatabaseSeeder. And do not override run method.
  2. Create DatabaseSeeder in modules/User/database/seeders directory. It must extend BaseDatabaseSeeder
  3. Create UserSeeder in modules/User/database/seeders directory. It must extends Illuminate\Database\Seeder
  4. Register UserSeeder in DatabaseSeeder's $earlySeeders or $seeders property.

Loaders

Inside ModuleServiceProvider we have different loaders:

Routes

web.php

Route::get('/index', [UserController::class, 'index'])->name('index');

api.php

Route::get('/index', [UserController::class, 'index'])->name('index');