Laravel Custom Artisan Commands

Laravel Custom Artisan Commands

You can build your own Artisan commands to automate tasks specific to your application.

1 - Generating a Command

php artisan make:command SendDailyReport

2 - Writing the Command

namespace App\Console\Commands;

use App\Models\User;
use App\Notifications\DailyReport;
use Illuminate\Console\Command;

class SendDailyReport extends Command
{
    protected $signature = 'report:send
                            {--type=summary : Report type (summary|full)}
                            {--email= : Override recipient email}';

    protected $description = 'Send daily report email to administrators';

    public function handle(): int
    {
        $type  = $this->option('type');
        $email = $this->option('email');

        $this->info("Sending $type report...");

        $admins = User::role('admin')->when($email, fn ($q) => $q->where('email', $email))->get();

        $admins->each->notify(new DailyReport($type));

        $this->info("Sent to {$admins->count()} admin(s).");

        return Command::SUCCESS;
    }
}

3 - Input and Output

// Arguments and options
$name = $this->argument('name');
$flag = $this->option('verbose');

// Interactive prompts
$name  = $this->ask('What is your name?');
$pass  = $this->secret('Enter password:');
$ok    = $this->confirm('Are you sure?');
$choice = $this->choice('Pick a plan', ['basic', 'pro', 'enterprise'], 0);

// Output
$this->info('Done!');
$this->warn('Warning!');
$this->error('Something failed!');
$this->table(['Name', 'Email'], User::select('name', 'email')->get()->toArray());