Skip to content

React to module lifecycle events

To run code when the Blog module is enabled or disabled, listen to its lifecycle events in your application. You need an enabled Blog module.

Modules fire string events named modules.{lowercase name}.{event} with the Nwidart\Modules\Module instance as the payload. Register listeners in your application, not inside the module. When enabled fires, the process booted before the module was enabled, so module listeners are not registered yet.

  1. Register a listener in the boot() method of an application service provider.

    app/Providers/AppServiceProvider.php
    <?php
    namespace App\Providers;
    use Illuminate\Support\Facades\Event;
    use Illuminate\Support\Facades\Log;
    use Illuminate\Support\ServiceProvider;
    use Nwidart\Modules\Module;
    class AppServiceProvider extends ServiceProvider
    {
    public function boot(): void
    {
    Event::listen('modules.blog.enabled', function (Module $module) {
    Log::info("Module {$module->getName()} enabled.");
    });
    }
    }
  2. Use a wildcard to listen across all modules. Wildcard listeners receive the event name and an array containing the payload.

    app/Providers/AppServiceProvider.php
    Event::listen('modules.*.disabled', function (string $event, array $payload) {
    [$module] = $payload;
    Log::info("Module {$module->getName()} disabled.");
    });
  3. Check the result. Disable and enable the module, then inspect the log.

    Terminal window
    php artisan module:disable Blog
    php artisan module:enable Blog
    tail -n 2 storage/logs/laravel.log
    [<time>] local.INFO: Module Blog disabled.
    [<time>] local.INFO: Module Blog enabled.

Modules fire events around creation (creating, created), status changes (enabling, enabled, disabling, disabled), deletion (deleting, deleted), and active selection (used, unused). See Events for the complete list, triggers, and payloads.