Skip to content

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.

  1. Generate the command with --command to set its signature.

    Terminal window
    php artisan module:make-command PruneOldPosts Blog --command=blog:prune-old

    This creates Modules/Blog/app/Console/PruneOldPosts.php (Modules\Blog\Console\PruneOldPosts).

  2. Implement handle().

    Modules/Blog/app/Console/PruneOldPosts.php
    <?php
    namespace 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.');
    }
    }
  3. Register the class in the $commands property 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,
    ];
  4. Check the result by listing the module’s commands and running the new command.

    Terminal window
    php artisan module:list-commands Blog

    The output lists blog:prune-old under Blog/Console.

    Terminal window
    php artisan blog:prune-old
    Old posts pruned.