Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Modules Laravel Package

nwidart/laravel-modules

Modularize large Laravel apps with nwidart/laravel-modules. Create self-contained modules (controllers, models, views, routes, config) with Artisan generators, module discovery, enabling/disabling, and per-module resources—tested and maintained across modern Laravel versions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require nwidart/laravel-modules
    

    The package auto-registers its service provider and aliases.

  2. Publish Configuration (Optional)

    php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider"
    
  3. Enable Composer Merge Plugin Add to composer.json:

    "extra": {
        "merge-plugin": {
            "include": ["Modules/*/composer.json"]
        }
    },
    "config": {
        "allow-plugins": {
            "wikimedia/composer-merge-plugin": true
        }
    }
    

    Run:

    composer dump-autoload
    
  4. Create Your First Module

    php artisan module:make Blog
    

    This generates a module skeleton in Modules/Blog/ with:

    • ModuleServiceProvider
    • routes/web.php/routes/api.php
    • Http/Controllers/ (empty by default)
    • Database/Migrations/
    • Resources/views/
  5. Enable the Module

    php artisan module:enable Blog
    

First Use Case: Adding a Controller

php artisan module:make-controller Blog Post --web

This creates Modules/Blog/Http/Controllers/PostController.php with a web route stub.


Implementation Patterns

Core Workflows

1. Modular Development Cycle

  • Create a Module:
    php artisan module:make <ModuleName>
    
  • Generate Resources:
    php artisan module:make-model Blog Post
    php artisan module:make-controller Blog Post --web
    php artisan module:make-migration Blog create_posts_table
    
  • Seed Data:
    php artisan module:seed Blog --class=PostTableSeeder
    
  • Enable/Disable:
    php artisan module:enable/disable <ModuleName>
    

2. Routing

  • Modules auto-register routes via RouteServiceProvider (generated in Modules/<Module>/Routes/).
  • Override defaults by publishing stubs:
    php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider" --tag="stubs"
    

3. Asset Compilation

  • Use Laravel Mix/Vite in modules:
    • Place vite.config.js or webpack.mix.js in the module root.
    • Load assets via:
      import './Resources/assets/js/app.js';
      
    • Run builds with:
      npm run dev --prefix Modules/<Module>
      

4. Service Providers

  • Modules register their ModuleServiceProvider automatically.
  • Extend functionality by overriding the provider’s register()/boot() methods.

5. Database Migrations

  • Run module-specific migrations:
    php artisan module:migrate Blog
    
  • Rollback:
    php artisan module:migrate:rollback Blog
    

Integration Tips

Namespacing

  • Modules default to Modules/<Module>/ with namespace Modules\<Module>.
  • Customize via config/modules.php:
    'namespace' => 'App\\Modules',
    'path' => 'app/Modules',
    

Testing

  • Use --module flag in tests:
    $this->artisan('module:enable', ['module' => 'Blog'])->assertExitCode(0);
    
  • Mock module dependencies via Laravel’s testing helpers.

Event Handling

  • Modules include an EventServiceProvider by default (v11+).
  • Dispatch events from controllers/services:
    event(new PostCreated($post));
    

APIs vs Web Controllers

  • Generate API controllers with:
    php artisan module:make-controller Blog Post --api
    
  • Web controllers default to web middleware group.

Views and Components

  • Use Blade components:
    php artisan module:make-component Blog Alert
    
  • Share views across modules via view()->addNamespace().

Seeding

  • Seed specific modules:
    php artisan module:seed Blog --class=PostTableSeeder
    
  • Use --force to overwrite existing data.

Gotchas and Tips

Pitfalls

1. Autoloading Issues

  • Symptom: Class not found errors for module classes.
  • Fix:
    • Ensure composer dump-autoload is run after adding modules.
    • Verify merge-plugin is enabled in composer.json.
    • Check for typos in module namespaces (e.g., Modules\Blog vs Modules\blog).

2. Route Conflicts

  • Symptom: Routes from multiple modules clash.
  • Fix:
    • Use module-specific route prefixes:
      Route::prefix('blog')->group(function () { ... });
      
    • Disable unused modules during development:
      php artisan module:disable UnusedModule
      

3. Migration Failures

  • Symptom: Table already exists errors.
  • Fix:
    • Use --force for migrations:
      php artisan module:migrate Blog --force
      
    • Check for duplicate migration files (e.g., timestamps in filenames).

4. Asset Loading Failures

  • Symptom: CSS/JS not loading in module views.
  • Fix:
    • Ensure vite.config.js or webpack.mix.js exists in the module root.
    • Verify asset paths in Blade templates:
      @vite(['resources/css/app.css', 'Modules/Blog/Resources/css/blog.css'])
      
    • Clear cached assets:
      php artisan optimize:clear
      

5. Module Activation Persistence

  • Symptom: Modules revert to disabled after server restart.
  • Fix:
    • Use the File Activator (default) or switch to Database Activator:
      php artisan module:v6:migrate
      
    • Configure in config/modules.php:
      'activator' => \Nwidart\Modules\Activators\DatabaseActivator::class,
      

Debugging Tips

1. Check Module Status

php artisan module:list
  • Output shows enabled/disabled modules and their paths.

2. Verify Service Provider Registration

  • Check config/app.php for:
    'providers' => [
        // ...
        Nwidart\Modules\ModulesServiceProvider::class,
    ],
    

3. Inspect Route Registration

  • Dump registered routes:
    Route::get('/debug/routes', function () {
        return collect(Route::getRoutes()->getByName())->count();
    });
    

4. Debug Asset Compilation

  • Run Vite/Mix in debug mode:
    npm run dev --prefix Modules/Blog -- --debug
    

5. Log Module Events

  • Enable module logging in config/modules.php:
    'log' => true,
    
  • Check storage/logs/laravel.log for module-related entries.

Extension Points

1. Custom Generators

  • Extend Artisan commands by publishing stubs:
    php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider" --tag="stubs"
    
  • Override stubs in Modules/<Module>/stubs/.

2. Module Activators

  • Implement custom activators (e.g., Redis, Cache):
    class CacheActivator implements ActivatorContract {
        public function isEnabled(string $module): bool { ... }
        public function enable(string $module): void { ... }
        public function disable(string $module): void { ... }
    }
    
  • Register in config/modules.php:
    'activator' => App\Modules\CacheActivator::class,
    

3. Dynamic Module Loading

  • Load modules conditionally (e.g., based on user roles):
    if (auth()->user()->isAdmin()) {
        Module::enable('AdminPanel');
    }
    

4. Module-Specific Config

  • Use config() with module-specific keys:
    config(['modules.blog.enabled' => true]);
    
  • Publish module configs:
    php artisan vendor:publish --tag=blog-config
    

5. Testing Modules

  • Mock module dependencies in tests:
    $this->partialMock(Module::class, 'isEnabled')
         ->shouldReturn(true);
    
  • Use --module flag for module-specific tests:
    php artisan test --module=Blog
    

Pro Tips

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata