Twinkle
Creating a Custom Laravel Artisan Command
Laravel's Artisan command line interface provides a number of helpful commands for development. Creating your own custom command allows you to automate specific tasks for your application.
Step 1: Generate the Command File
Use the make:command
Artisan command to create a new command class:
php artisan make:command ProcessTransactions
This will create a new file at app/Console/Commands/ProcessTransactions.php
.
Step 2: Configure the Command
Open the generated file and customize these key properties:
protected $signature = 'app:process-transactions {date? : The date to process}';
protected $description = 'Process pending transactions in the system';
$signature
: Defines the command name and any arguments/options$description
: Provides help text about what the command does
Step 3: Implement the Handle Method
The handle()
method contains the logic executed when the command runs:
public function handle()
{
$date = $this->argument('date') ?? now()->toDateString();
$this->info("Processing transactions for: {$date}");
// Your command logic here
$count = Transaction::whereDate('created_at', $date)
->where('status', 'pending')
->get()
->each(function ($transaction) {
// Process each transaction
$this->processTransaction($transaction);
})
->count();
$this->info("{$count} transactions processed successfully!");
return Command::SUCCESS;
}
private function processTransaction($transaction)
{
// Transaction processing logic
$this->line("Processing transaction #{$transaction->id}");
// ...
}
Step 4: Register the Command (Laravel 8+)
For Laravel 8 and newer, commands are auto-discovered. For older versions, register your command in the app/Console/Kernel.php
file:
protected $commands = [
\App\Console\Commands\ProcessTransactions::class,
];
Step 5: Use the Command
Run your command from the terminal:
# Basic usage
php artisan app:process-transactions
# With an argument
php artisan app:process-transactions 2023-10-15
Advanced Features
- Questions & Confirmations: Use
$this->ask()
,$this->secret()
, or$this->confirm()
- Progress Bars: Use
$this->withProgressBar($items, function ($item) {...})
- Tables: Use
$this->table(['Header1', 'Header2'], $data)
- Scheduling: Add your command to the scheduler in
app/Console/Kernel.php
// In app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('app:process-transactions')->daily();
}
Custom Artisan commands are powerful tools for automating repetitive tasks and creating specialized workflows for your Laravel application.