Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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?

like image 580
did1k Avatar asked Jan 18 '13 07:01

did1k


2 Answers

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.

like image 173
William Turrell Avatar answered Nov 14 '22 22:11

William Turrell


class Sample_Task
{
    public function create($args) {
       $arg1 = $args[0];
       $arg2 = $args[1];
        // something here
    }
}
like image 7
ray Avatar answered Nov 14 '22 20:11

ray