Table Of Contents
Quick Fix: Command Parameters
Define arguments and options in your command's signature to accept user input.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class ProcessDataCommand extends Command
{
// Define arguments and options in signature
protected $signature = 'process:data
{file : The file to process}
{--type=csv : The file type (csv, json, xml)}
{--limit=100 : Number of records to process}
{--dry-run : Run without making changes}
{--email=* : Email addresses to notify}';
protected $description = 'Process data from various file formats';
public function handle()
{
// Get argument
$file = $this->argument('file');
// Get options
$type = $this->option('type');
$limit = $this->option('limit');
$isDryRun = $this->option('dry-run');
$emails = $this->option('email'); // Array for multiple values
$this->info("Processing: $file");
$this->info("Type: $type, Limit: $limit");
if ($isDryRun) {
$this->warn('Running in dry-run mode');
}
foreach ($emails as $email) {
$this->line("Will notify: $email");
}
}
}
// Advanced signature patterns
protected $signature = 'user:create
{email : The user email address}
{name? : Optional user name}
{role=user : Role with default value}
{--a|admin : Make user an admin}
{--force : Skip confirmation}
{--id=* : Multiple user IDs}';
// Array arguments (must be last)
protected $signature = 'mail:send
{recipients* : List of email recipients}
{--subject=}';
// Usage examples:
// php artisan process:data invoices.csv
// php artisan process:data data.json --type=json --limit=50
// php artisan process:data file.xml --dry-run --email=admin@site.com --email=dev@site.com
// Optional argument with default
protected $signature = 'cache:warm {store=redis : Cache store to warm}';
// Boolean flag shorthand
protected $signature = 'migrate:fresh {--s|seed : Seed the database}';
// Accessing all arguments/options at once
public function handle()
{
$arguments = $this->arguments(); // All arguments as array
$options = $this->options(); // All options as array
// Check if option was explicitly passed
if ($this->hasOption('force') && $this->option('force')) {
// Force mode enabled
}
}
Signature Syntax Rules in Laravel 11
Arguments use {}
and are required by default. Add ?
for optional, =default
for defaults. Options use --
prefix, are always optional, and can have defaults or accept multiple values with =*
.
In Laravel 8 through 11, array arguments must be the last argument. Options can have single-letter aliases using |
. Boolean options are false by default, true when passed.
Common patterns: "Required positional arguments", "Optional flags for modes", "Multiple values for batch operations". Always validate input in the handle method.
Alternative approaches include prompting for missing values with ask()
, using configuration files for complex options, or environment variables for defaults.
Add Comment
No comments yet. Be the first to comment!