Spread the love

Laravel artisan provides several inbuilt commands to help the developer to build a robust applications like to create the controller, models, migration etc. and in this article i will show you to create your own custom artisan command in laravel. This custom artisan can be configure according to your needs and will help you to build easily your application.

Artisan commands can be called from terminal as well from code programmatically in laravel. Laravel provides two methods to register your custom commands, first is by registering it in routes/console.php and second one is by generating the console class and then register it to kernel.php file.

Both methods are configurable and can be called from command line. In this article i will create a simple command using php artisan and also by registering in routes/console.php. Also we will understand the usage of options, arguments, default parameters, description and help.

Let’s start the tutorial of Create a Custom Artisan Command in Laravel step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Generate a Console Command

As mentioned above we can create console command in two ways lets create the first by registering in routes/console.php

<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

Artisan::command('simpledemo', function () {
    
    $this->comment("This is a comment ");
    // \DB::table("recent_users")->delete();
    //or any logging
     
})->purpose('Demo of artisan command');

here we created a simple command with name simpledemo and in closure function we simply outputting a comment.

we can run above command as follow

php artisan simpledemo

Output :

This is a comment

Let’s deep dive into this by adding more options to it


Artisan::command('simpledemo {user} {optionalArg?} {defaultArg=2} {--Q|queue} {--queueWithVal=} {--queueWithDefaultVal=default}', function (
    $user,
    $optionalArg = 0,
    $defaultArg,
    $queue,
    $queueWithVal,
    $queueWithDefaultVal
) {
    $this->comment("This is a comment " . $optionalArg);
    $this->info("This is an info with " . $this->argument('user'));
    $this->error("This is an error " . $defaultArg);
    $this->info("Queue option " . ($queue ? "Enabled" : "Disabled"));
    $this->info("Queue with value " . $queueWithVal);
    $this->info("Queue with queueWithDefaultVal " . $queueWithDefaultVal);

   $answer= $this->ask('What is your name?');
   if ($this->confirm('Do you wish to continue?')) {
    $this->info("Your Answer is " . $answer);
   }
   else{
    $this->info("You denied");
   }
  
})->purpose('Demo of artisan command');

Here i added options, help, short key, arguments and arguments with default parameter.

Let’s run this

php artisan simpledemo 1 3 5  --queueWithVal=test --queueWithDefaultVal=passedfromterminal -Q

Output :

This is a comment 3
This is an info with 1
This is an error 5
Queue option Enabled
Queue with value test
Queue with queueWithDefaultVal passedfromterminal

 What is your name?:
 > readerstacks

 Do you wish to continue? (yes/no) [no]:
 > yes

Your Answer is readerstacks

Console command using class

In this method we will generate a class using artisan command. All options and methods are same only difference is we will create a separate class to handle the command so let’s create a command

php artisan make:command Demo

this will create a class in app/Console/Commands/Demo.php and update the class as follow

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Demo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:init {user} {optionalArg?} {defaultArg=2} {--Q|queue} {--queueWithVal=} {--queueWithDefaultVal=default}';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->comment("This is a comment " . $this->argument('optionalArg'));
        $this->info("This is an info with " . $this->argument('user'));
        $this->error("This is an error " . $this->argument('defaultArg'));
        $this->info("Queue option " . ($this->option('queue') ? "Enabled" : "Disabled"));
        $this->info("Queue with value " . $this->option('queueWithVal'));
        $this->info("Queue with queueWithDefaultVal " . $this->option('queueWithDefaultVal'));

        $answer = $this->ask('What is your name?');
        if ($this->confirm('Do you wish to continue?')) {
            $this->info("Your Answer is " . $answer);
        } else {
            $this->info("You denied");
        }
    }
}

Step 3 : Run Command

Let’s test the implementation by ruining artisan command

php artisan demo:init  1 3 5  --queueWithVal=test --queueWithDefaultVal=passedfromterminal -Q

Output:

This is a comment 3
This is an info with 1
This is an error 5
Queue option Enabled
Queue with value test
Queue with queueWithDefaultVal passedfromterminal

 What is your name?:
 > readerstacks

 Do you wish to continue? (yes/no) [no]:
 > no

You denied

We can also call above command programmatically as follow

use Illuminate\Support\Facades\Artisan;
 
Route::post('/call-artisan', function ($user) {
    $exitCode = Artisan::call('demo:init', [
        'user' => 1, '--queueWithDefaultVal' => 'default'
    ]);
 
    //
});

Leave a Reply