How to Add a New Artisan Command in Laravel

When working with the Laravel framework, of course we are familiar with the php artisan command. Without this command working with Laravel would not be as easy as now. If you don’t know, we can add our own custom commands to artisan command. If you like to work automatically and like to work with the command line, I think adding your own artisan commands can increase your productivity.

To add an artisan command use this command in the terminal.

php artisan make:command file_name

You can fill the file_name argument with any words as long as it is in compliance with the class naming convention in php, later this file_name argument will be used by laravel as the base for creating the file and class. For example, if I type the command like below.

php artisan make:command CreateUserCommand

Then Laravel will create a file with the name of CreateUserCommand.php in the app/Console/Commands folder with the following content.

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateUserCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
    }
}

Add your new command that can be called via the artisan command in the $signature property. For example, if we fill it like below.

protected $signature = 'create:user';

In the terminal, we can call the new artisan command above with this way.

php artisan create:user

Next, fill in the $description property. You can fill this property with any words regarding the functionality of this command, for example you kan fill it like this.

protected $description = 'Create Random User';

Next, make sure that the create:user command that we just created is registered and recognised by laravel by typing this command in terminal.

php artisan list
List of artisan command in laravel php framework

From the picture above, it can be seen that the create:user command that we just created is already registered and recognised by laravel. Congrats.

When your new command is called via the artisan command, laravel will execute the handle() method. Therefore place your command logic in this method. For example, we can display a simple message, as below.

public function handle()
{
    $this->info('You call create:user command');
}

Next, we can test it by running a command like below.

Test new artisan command in laravel php framework

We can also add several positional arguments to the commands that we make as below.

protected $signature = '
        create:user
        {first_argument}
        {second_argument}
    ';

Positional arguments are arguments that laravel read based on their position that was typed in the terminal. Usually, positional arguments are separated by spaces.

To get the argument’s value that the user type, we can use the code as below.

public function handle()
{
    $first_argument = $this->argument('first_argument');
    $second_argument = $this->argument('second_argument');
    
    $this->info("
            You call create:user command \n
            with First Argument : {$first_argument}
            and Second Argument : {$second_argument}
        ");
}

When we type commands like this in terminal.

php artisan create:user Ngasturi Surabaya

The word Ngasturi will be recognised as the first argument because it was written first. If the argument contains spaces, wrap the argument in a single or double quote, as shown below.

php artisan create:user Ngasturi 'Jalan Ahamad Yani 12 Surabaya'

The console will appear as shown below.

An example of how to call a new artisan command with argument

Positional arguments can also have default values like this.

protected $signature = '
    create:user
    {first_argument}
    {second_argument=Jakarta}
';

So if we don’t fill in the second_argument when we type the command in terminal, the value will be automatically filled with the word of ‘Jakarta’.

Apart from arguments, we can also use the option as shown below.

protected $signature = '
    create:user
    {first_argument}
    {second_argument=Jakarta}
    {--first_option=}
    {--second_option=}
';

Unlike the arguments, we can write the options out of order, but must be written after all the positional arguments have been written, as shown below.

An example of how to call a new artisan command with argument and option

To get the options that typed by the user, we can use the code like below.

public function handle()
{
    $first_argument = $this->argument('first_argument');
    $second_argument = $this->argument('second_argument');

    $first_option = $this->option('first_option');
    $second_option = $this->option('second_option');
    
    $this->info("
            You call create:user command \n
            with First Argument : {$first_argument}
            and Second Argument : {$second_argument}

            with First Option : {$first_option}
            and Second Option : {$second_option}
        ");
}

This is a complete example of an artisan command for creating a random user.

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use App\User;

class CreateUserCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '
                            create:user
                            {--name=}
                            {--email=}
                            {--password=}
                        ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create Random User';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $name = empty($this->option('name')) ? $this->generateRandomString() : $this->option('name');
        $email = empty($this->option('email')) ? $this->generateRandomString() . '@' . $this->generateRandomString() . '.com' : $this->option('email');
        $password = empty($this->option('password')) ? $this->generateRandomString(8) : $this->option('password');

        User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
        ]);
        
        $this->info("
                Successfully create new User with this credential \n
                Name : {$name}
                Email : {$email}
                Password : {$password}
            ");
    }

    private function generateRandomString($length = 4) {
        return substr(str_shuffle(str_repeat($x='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
    }
}

We can use above command in terminal like the picture below.

Execute an artisan command to create random user in laravel
Execute an artisan command to create random user with specified name in laravel
Execute an artisan command to create random user with specified email and password in laravel
Related Article

Leave a Reply