lazerg / laravel-modular
Laravel Modular
Requires
- php: ^8.0
- laravel/framework: ^11.0
README
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
- Move
/app/Modules/User
to/modules/User/app/Modes/User
- Change
auth.providers.users.model
config toModules\User\Models\User
. - Move
/database/migrations/2014_10_12_000000_create_users_table.php
to/modules/User/database/migrations/2014_10_12_000000_create_users_table.php
- Move
/database/factories/UserFactory.php
to/modules/User/database/factories/UserFactory.php
Setup seeder
database/seeders/DatabaseSeeder.php
must extendModularDatabaseSeeder
. And do not overriderun
method.- Create
DatabaseSeeder
inmodules/User/database/seeders
directory. It must extendBaseDatabaseSeeder
- Create
UserSeeder
inmodules/User/database/seeders
directory. It must extendsIlluminate\Database\Seeder
- Register
UserSeeder
inDatabaseSeeder
'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');