skip to Main Content

I am creating a custom Artisan command in Laravel, and I need to pass parameters to the handle() function. However, I’m not sure how to define and access these parameters when running the command.

Here’s what I have so far:

class UpdatePlacesImages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:update-places-images';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch places data(specially images) from Places API and save it in the goog_data field';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        /* We are updating google_data field by using two separate functions 
        1: updatePlacesImages()
            Updating ""google_data"" field using ""place_id"" for all places ""Expect Lounges"" because Lounges places
            are stored in table name ""lounges"" and DB name ""newairport"" while the remaining all places are 
            saved in table name ""places"" and DB name ""airport_remote  
            
        2: updateLoungesImages()
            Updating ""google_data"" field using ""place_id""  only for lounges place
        */

        $this->updatePlacesImages();
        $this->updateLoungesImages();
    }
}

What I Want:

1: I want to pass a parameter places or lounges.

Example:

1: php artisan app:update-places-images places

or

2: php artisan app:update-places-images lounges

2

Answers


  1. Change your signature to

    protected $signature = 'app:update-places-images {argument}';
    

    This is how you can fetch it

    public function handle(): void
    {
        $argument = $this->argument('argument');
    }
    

    Since you want your places OR lounges to be the parameter, you cannot in advance determine whether you will receive places or lounges, therefore you’ll need some functionality based on which you will be able to determine whether argument is actually places or lounges.

    Login or Signup to reply.
  2. You can use accept options from the signature like this:

    protected $signature = 'app:update-places-images {places} {lounges}';
    

    Then retrieve them like below:

    public function handle(): void
    {
       $places = $this->option('places');
       $lounges = $this->option('lounges');
    
    }
    

    Alternatively, you retrieve everything as an array by doing this:

    public function handle(): void
    {
       $options = $this->options();
    }
    

    You can read more here: https://laravel.com/docs/11.x/artisan#options

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search