Laravel Command Multiple Arguments

Laravel Command with Multiple Arguments

In Laravel, you can create custom console commands to perform various tasks. These commands can accept multiple arguments which can be used to customize the behavior of the command. Let’s understand how to define a Laravel command with multiple arguments using an example.

Step 1: Create the Command

First, create a new command using the Artisan command line tool. Open your terminal and run the following command:

php artisan make:command MyCommand

This will create a new file named “MyCommand.php” inside the “app/Console/Commands” directory. Open this file and locate the `handle` method. This method is responsible for the execution logic of your command.

Step 2: Define the Arguments

Inside the `handle` method, you can define your command’s arguments using the `$this->argument` method. You can pass the argument name as the first parameter and an optional default value as the second parameter.

public function handle()
  {
      $arg1 = $this->argument('arg1');
      $arg2 = $this->argument('arg2');
      
      // Your command logic here
  }
  

Step 3: Run the Command

Now you can run your command by calling its name from the Artisan command line tool with the specified arguments. For example:

php artisan my:command argument1_value argument2_value
  

Replace “my:command” with the actual name of your command and “argument1_value” and “argument2_value” with the desired values for your arguments.

Example

Let’s assume we want to create a command that generates a greeting message using a person’s name and an optional language argument. Open the “MyCommand.php” file and update the `handle` method as follows:

public function handle()
  {
      $name = $this->argument('name');
      $language = $this->argument('language') ?? 'english';
      
      $greeting = $this->getGreeting($name, $language);
      
      $this->info($greeting);
  }
  
  private function getGreeting($name, $language)
  {
      switch ($language) {
          case 'french':
              return "Bonjour, $name!";
          case 'spanish':
              return "¡Hola, $name!";
          default:
              return "Hello, $name!";
      }
  }
  

Now, when you run the command with the name and language arguments:

php artisan my:command John french
  

It will output: “Bonjour, John!”

If you don’t provide the language argument:

php artisan my:command Jane
  

It will output: “Hello, Jane!” as the default language is set to ‘english’.

That’s it! You have now created a Laravel command with multiple arguments. You can customize the command and its arguments based on your requirements.

Read more

Leave a comment