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

zingle-com/laravel-modules

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require zingle-com/laravel-modules
    

    Register the ModuleServiceProvider in config/app.php after Laravel core providers but before custom providers.

  2. Publish Assets:

    php artisan vendor:publish --provider="ZingleCom\LaravelModules\ModuleServiceProvider"
    

    This generates a config/modules.php file with default settings.

  3. Create a Module:

    php artisan module:make Blog
    

    This scaffolds a module directory (app/Modules/Blog) with:

    • Module.php (core class)
    • Providers/ (for service providers)
    • Http/ (routes, controllers)
    • Resources/ (views, assets)
  4. Register the Module: Add the module to config/modules.php under modules array:

    'modules' => [
        'Blog' => [
            'path' => 'app/Modules/Blog',
            'is_core' => false,
            'providers' => [
                'BlogServiceProvider',
            ],
            'routes' => [
                'web' => 'routes/web.php',
            ],
        ],
    ],
    
  5. First Use Case: Load module routes in routes/web.php:

    Route::module('Blog');
    

Implementation Patterns

Core Workflows

  1. Module Initialization:

    • Modules auto-load via ModuleServiceProvider when registered in config/modules.php.
    • Use Module::load('Blog') to manually load a module (e.g., in a command or middleware).
  2. Service Providers:

    • Place module-specific providers in Providers/ (e.g., BlogServiceProvider.php).
    • Register providers in config/modules.php under the module’s providers key.
    • Example:
      class BlogServiceProvider extends ServiceProvider {
          public function register() {
              $this->app->singleton('blog.repository', function () {
                  return new BlogRepository();
              });
          }
      }
      
  3. Routing:

    • Define routes in Http/routes/web.php (or api.php).
    • Load routes via Route::module('ModuleName') in your main web.php.
    • Dynamic Routes: Use Route::module('Blog')->group(function () { ... }) for scoped routes.
  4. Views and Assets:

    • Publish views to resources/views/modules/{ModuleName}/.
    • Use @module('Blog') directive in Blade templates to load module-specific views:
      @module('Blog')
          @include('blog::home')
      @endmodule
      
    • Publish assets (CSS/JS) via php artisan module:publish-assets Blog.
  5. Middleware:

    • Apply module-specific middleware in Http/Kernel.php:
      protected $moduleMiddleware = [
          'Blog' => [
              \App\Modules\Blog\Http\Middleware\Authenticate::class,
          ],
      ];
      
    • Register middleware in config/modules.php:
      'Blog' => [
          'middleware' => ['auth.blog'],
      ],
      
  6. Commands and Jobs:

    • Place commands in Console/Commands/ and jobs in Jobs/ within the module.
    • Register commands in BlogServiceProvider:
      $this->commands([
          \App\Modules\Blog\Console\Commands\BackupCommand::class,
      ]);
      
  7. Database Migrations:

    • Store migrations in Database/Migrations/ within the module.
    • Run migrations via:
      php artisan module:migrate Blog
      
    • Rollback:
      php artisan module:migrate:rollback Blog
      
  8. Testing:

    • Use php artisan module:test Blog to run module-specific tests.
    • Tests should reside in Tests/Module/Blog/.

Integration Tips

  1. Dependency Management:

    • Use Module::dependencies() to define module dependencies (e.g., Blog depends on Auth):
      // app/Modules/Blog/Module.php
      public function dependencies() {
          return ['Auth'];
      }
      
    • Dependencies are loaded automatically when the module is loaded.
  2. Configuration:

    • Publish module-specific config files:
      php artisan module:publish-config Blog
      
    • Access config via config('blog.key').
  3. Event Handling:

    • Dispatch module events in Module.php:
      public function boot() {
          event(new ModuleBooted($this));
      }
      
    • Listen for events in your main EventServiceProvider.
  4. APIs and Controllers:

    • Use Route::module('Blog')->api() for API routes.
    • Controllers should extend BaseController from the module or use Laravel’s built-in controllers.
  5. Localization:

    • Place language files in Resources/lang/ within the module.
    • Load translations via __('blog::key').
  6. Caching:

    • Clear module-specific cache:
      php artisan module:clear-cache Blog
      

Gotchas and Tips

Pitfalls

  1. Service Provider Loading Order:

    • Ensure module providers are registered after the ModuleServiceProvider in config/modules.php.
    • Error: Class not found for module providers if loaded out of order.
  2. Route Caching:

    • Clear route cache after adding/removing module routes:
      php artisan route:clear
      
    • Symptom: Routes not appearing after adding Route::module().
  3. Namespace Conflicts:

    • Avoid naming modules the same as Laravel core classes (e.g., Auth, Cache).
    • Fix: Use unique module names (e.g., UserAuth instead of Auth).
  4. Middleware Not Triggering:

    • Ensure middleware is registered in both:
      • config/modules.php under middleware.
      • The module’s Kernel.php (if custom middleware is used).
    • Debug: Check Route::getRoutes() to verify middleware is attached.
  5. Asset Publishing Issues:

    • Run php artisan module:publish-assets Blog after compiling assets (e.g., after npm run dev).
    • Symptom: Assets not loading despite correct paths.
  6. Module Auto-Loading:

    • Modules marked as is_core: true in config/modules.php are loaded automatically on app boot.
    • Non-core modules require explicit loading via Module::load('Blog') or Route::module().
  7. Database Seeders:

    • Seeders should be placed in Database/Seeders/ and registered in BlogServiceProvider:
      $this->loadMigrationsFrom(__DIR__.'/../Database/Migrations');
      $this->loadSeedersFrom(__DIR__.'/../Database/Seeders');
      
    • Run seeds with:
      php artisan module:seed Blog
      
  8. Testing Modules:

    • Mock module dependencies in tests:
      $this->partialMock(Module::class, 'dependencies')
           ->shouldReturn(['MockDependency']);
      
    • Tip: Use php artisan module:test Blog --env=testing for isolated testing.

Debugging Tips

  1. Check Module Status:

    php artisan module:list
    
    • Lists loaded/unloaded modules and their status.
  2. Enable Debugging:

    • Set debug to true in config/modules.php to log module events:
      'debug' => env('MODULES_DEBUG', false),
      
  3. Common Errors and Fixes:

    Error Solution
    Class 'Module' not found Ensure use ZingleCom\LaravelModules\Module; is added to your file.
    Module not registered Add the module to config/modules.php.
    Route [module.route] not defined Verify Route::module('ModuleName') is called in your main routes file.
    Table not found (migrations) Run php artisan module:migrate ModuleName.
    View not found Ensure the view exists in resources/views/modules/ModuleName/.
  4. Log Module Events:

    • Add this to Module.php to log events:
      public function boot() {
          \Log::info("Module {$this->getName()} booted.");
      }
      

Extension Points

  1. Custom Module Classes:

    • Extend ZingleCom\LaravelModules\Module to add custom logic:
      class BlogModule extends Module {
          public function extraLogic() {
              // Custom initialization
          }
      }
      
  2. Dynamic Module Loading:

    • Load modules conditionally in ModuleServiceProvider:
      if ($this->app->environment('local')) {
          Module
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle