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.
-
Register a listener in the
boot()method of an application service provider.app/Providers/AppServiceProvider.php <?phpnamespace 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.");});}} -
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.");}); -
Check the result. Disable and enable the module, then inspect the log.
Terminal window php artisan module:disable Blogphp artisan module:enable Blogtail -n 2 storage/logs/laravel.log[<time>] local.INFO: Module Blog disabled.[<time>] local.INFO: Module Blog enabled.
Available lifecycle events
Section titled “Available lifecycle events”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.
Related
Section titled “Related”- Events: every event, its trigger and its payload.
module:enableandmodule:disable- Enable and disable modules
- Use events and listeners in a module