Retrieving Command Parameters in Laravel Artisan
Last updated on by Harris Raftopoulos
Laravel provides straightforward methods for accessing arguments and options within your custom Artisan commands. These built-in helpers simplify parameter retrieval and validation.
Access individual parameters using dedicated methods:
$username = $this->argument('username'); $environment = $this->option('env');
You can also retrieve all parameters at once when building dynamic command processors or debugging utilities.
$allArguments = $this->arguments(); $allOptions = $this->options();
Here's a backup management command that demonstrates comprehensive parameter handling:
class BackupDatabase extends Command{ protected $signature = 'backup:database {database : Database name to backup} {--path= : Custom backup directory} {--compress : Compress the backup file} {--exclude=* : Tables to exclude from backup} {--S|silent : Run without output}'; public function handle() { $databaseName = $this->argument('database'); $backupPath = $this->option('path') ?? storage_path('backups'); $shouldCompress = $this->option('compress'); $silent = $this->option('silent'); if (!$silent) { $this->line("Starting backup for database: {$databaseName}"); $this->line("Backup location: {$backupPath}"); } if ($shouldCompress) { $this->info('Compression enabled'); } $excludedTables = $this->option('exclude'); if (!empty($excludedTables)) { $this->warn('Excluding tables: ' . implode(', ', $excludedTables)); } $allParams = $this->arguments(); $allFlags = $this->options(); if ($this->option('verbose')) { $this->table(['Parameter Type', 'Count'], [ ['Arguments', count($allParams)], ['Options', count($allFlags)] ]); } }}
Laravel's parameter access methods enable you to build robust command-line tools that handle complex input scenarios with minimal code complexity.