How to Create Custom Artisan Command

How to Create Custom Artisan Command

Learn how to create and use custom Artisan commands in Laravel to automate tasks and improve your workflow.

Introduction

Laravel's Artisan command-line interface provides a powerful way to interact with your application. This guide will show you how to create custom Artisan commands to automate tasks, process data, and perform maintenance operations.

Prerequisites

  • Laravel 6.x or higher
  • Basic understanding of Laravel
  • Familiarity with command-line interfaces

1 Generate Command Class

Create a new command using Artisan:

php artisan make:command SendEmails

This will create a new command class in `app/Console/Commands/SendEmails.php`:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SendEmails extends Command
{
    protected $signature = 'emails:send {user} {--queue}';
    protected $description = 'Send emails to users';

    public function handle()
    {
        // Command logic here
    }
}

2 Define Command Signature

Configure the command signature with arguments and options:

protected $signature = 'emails:send
    {user : The ID of the user}
    {--queue : Whether to queue the emails}
    {--type=* : The types of emails to send}';

Available argument types:

  • {argument} - Required argument
  • {argument?} - Optional argument
  • {argument=default} - Optional with default value
  • {argument*} - Array argument
  • {argument?*} - Optional array argument

3 Implement Command Logic

Add your command logic in the handle method:

public function handle()
{
    $userId = $this->argument('user');
    $shouldQueue = $this->option('queue');
    $types = $this->option('type');

    $this->info('Starting email send process...');

    try {
        $user = User::findOrFail($userId);
        
        foreach ($types as $type) {
            if ($shouldQueue) {
                SendEmailJob::dispatch($user, $type);
                $this->info("Queued {$type} email for user {$user->name}");
            } else {
                Mail::to($user)->send(new EmailNotification($type));
                $this->info("Sent {$type} email to user {$user->name}");
            }
        }

        $this->info('Email process completed successfully!');
    } catch (\Exception $e) {
        $this->error('Failed to send emails: ' . $e->getMessage());
        return 1;
    }

    return 0;
}

4 Register Command

Register your command in `app/Console/Kernel.php`:

protected $commands = [
    Commands\SendEmails::class,
];

Note: In newer Laravel versions, commands are auto-discovered.

5 Using the Command

Run your command using Artisan:

# Basic usage
php artisan emails:send 1

# With options
php artisan emails:send 1 --queue

# With multiple options
php artisan emails:send 1 --queue --type=welcome --type=newsletter

# Get help
php artisan emails:send --help

6 Command Output

Use various output methods:

// Basic output
$this->info('Success message');
$this->error('Error message');
$this->warn('Warning message');
$this->line('Regular message');

// Tables
$this->table(
    ['Name', 'Email'],
    User::all(['name', 'email'])->toArray()
);

// Progress bars
$users = User::all();
$bar = $this->output->createProgressBar(count($users));
$bar->start();

foreach ($users as $user) {
    // Process user
    $bar->advance();
}

$bar->finish();

Key Features Covered

  • Command generation
  • Signature definition
  • Argument handling
  • Option handling
  • Command registration
  • Output formatting

Best Practices

  • Use descriptive names
  • Provide helpful descriptions
  • Handle errors gracefully
  • Use appropriate exit codes
  • Add progress indicators

Common Issues

  • Missing command registration
  • Incorrect argument types
  • Missing error handling
  • Incorrect namespace
  • Missing dependencies