Add Artisan commands to a module
To add the blog:prune-old Artisan command to the Blog module, generate the class and register it in the module’s service provider. You need an enabled Blog module. Laravel auto-discovers commands only in app/Console/Commands, so module commands require explicit registration.
-
Generate the command with
--commandto set its signature.Terminal window php artisan module:make-command PruneOldPosts Blog --command=blog:prune-oldThis creates
Modules/Blog/app/Console/PruneOldPosts.php(Modules\Blog\Console\PruneOldPosts). -
Implement
handle().Modules/Blog/app/Console/PruneOldPosts.php <?phpnamespace Modules\Blog\Console;use Illuminate\Console\Attributes\Description;use Illuminate\Console\Attributes\Signature;use Illuminate\Console\Command;#[Signature('blog:prune-old')]#[Description('Delete the old posts of the blog')]class PruneOldPosts extends Command{public function handle(){$this->info('Old posts pruned.');}} -
Register the class in the
$commandsproperty of the module service provider (uncomment the property in the generated provider).Modules/Blog/app/Providers/BlogServiceProvider.php /*** Command classes to register.** @var string[]*/protected array $commands = [\Modules\Blog\Console\PruneOldPosts::class,]; -
Check the result by listing the module’s commands and running the new command.
Terminal window php artisan module:list-commands BlogThe output lists
blog:prune-oldunderBlog/Console.Terminal window php artisan blog:prune-oldOld posts pruned.