Navigation

Laravel

How to Create a Custom Artisan Command

Build custom Laravel Artisan commands for repetitive tasks. Automate workflows with command-line tools that integrate with your application.

Problem: You have repetitive tasks like data cleanup, report generation, or batch processing that you want to automate through the command line.

Solution:

// Generate command skeleton
php artisan make:command SendNewsletterCommand

// In app/Console/Commands/SendNewsletterCommand.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Mail\NewsletterMail;
use Illuminate\Support\Facades\Mail;

class SendNewsletterCommand extends Command
{
    // Command signature - how you call it
    protected $signature = 'newsletter:send 
                            {type : The type of newsletter to send}
                            {--test : Send only to test users}
                            {--limit=100 : Number of users to process}';
    
    // Command description shown in artisan list
    protected $description = 'Send newsletter to subscribed users';
    
    public function handle()
    {
        $type = $this->argument('type');
        $isTest = $this->option('test');
        $limit = $this->option('limit');
        
        $this->info("Sending {$type} newsletter...");
        
        $query = User::where('subscribed', true);
        
        if ($isTest) {
            $query->where('is_test', true);
        }
        
        $users = $query->limit($limit)->get();
        
        $bar = $this->output->createProgressBar($users->count());
        
        foreach ($users as $user) {
            Mail::to($user)->queue(new NewsletterMail($type));
            $bar->advance();
        }
        
        $bar->finish();
        $this->newLine();
        $this->info('Newsletter sent successfully!');
        
        return Command::SUCCESS;
    }
}

// Usage
php artisan newsletter:send weekly
php artisan newsletter:send daily --test --limit=10

// Schedule in app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('newsletter:send daily')->dailyAt('09:00');
}

Why it works: Artisan commands have access to your entire Laravel application. The signature property defines arguments and options using a simple syntax. The handle() method contains your command logic with access to helpful console methods.

Pro tips: Use Command::SUCCESS (0) or Command::FAILURE (1) as return values. Add --no-interaction flag support for automated environments.

Table Of Contents

Related Topics

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel