Home » Php » php – How to pass multiple arguments when running Laravel Tasks on command line?

php – How to pass multiple arguments when running Laravel Tasks on command line?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I created a Task class with method that needs multiple arguments:

class Sample_Task
{
    public function create($arg1, $arg2) {
        // something here
    }
}

But it seems that artisan only gets the first argument:

php artisan sample:create arg1 arg2

Error message:

Warning: Missing argument 2 for Sample_Task::create()

How to pass multiple arguments in this method?

How to&Answers:
class Sample_Task
{
    public function create($args) {
       $arg1 = $args[0];
       $arg2 = $args[1];
        // something here
    }
}

Answer:

Laravel 5.2

What you need to do is specify the argument (or option, e.g. –option) in the $signature property as an array. Laravel indicates this with an asterisk.

Arguments

e.g. supposing you have an Artisan command to “process” images:

protected $signature = 'image:process {id*}';

If you then do:

php artisan help image:process

…Laravel will take care of adding the correct Unix-style syntax:

Usage:
  image:process <id> (<id>)...

To access the list, in the handle() method, simply use:

$arguments = $this->argument('id');

foreach($arguments as $arg) {
   ...
}

Options

I said it worked for options too, you use {--id=*} in $signature instead.

The help text will show:

Usage:
  image:process [options]

Options:
      --id[=ID]         (multiple values allowed)
  -h, --help            Display this help message

  ...

So the user would type:

php artisan image:process --id=1 --id=2 --id=3

And to access the data in handle(), you’d use:

$ids = $this->option('id');

If you omit ‘id’, you’ll get all options, including booleans for ‘quiet’,’verbose’ etc.

$options = $this->option();

You may access the list of IDs in $options['id']

More info in the Laravel Artisan guide.