Do not speak Portuguese? Translate this site with Google or Bing Translator
How to create a custom console command (artisan) for Laravel

Posted on: November 22, 2020 01:21 AM

Posted by: Renato

Categories: Laravel

Views: 443

Laravel has a command-line interface named Artisan. This interface provides the developer a lot of useful commands to speed up the development process.

Furthermore, you may want to extend artisan with your own commands to create and automatizate the unique tasks of your Laravel project. Commands are typically stored in the app/Console/Commands directory however, you are free to choose your own storage location as long as your commands can be loaded by Composer.

In this article, you'll learn how to create a custom command for artisan easily in Laravel 5.3.

Create and register command

Laravel help you to do everything easier, it has already integrated the make:console NewClassName command to speed up your development process. This command expects as first argument the name of the class and optionally, the command option to specify directly the name of the command without modify the class.

To create a new console command named quiz:start with class name QuizStart execute the following command in your console :

php artisan make:command QuizStart --command=quiz:start

 

Note: in case you don't want to use the console, copy the example class in "Structure of a command"and change the name of the file and class as you wish. Remember too that in previous versions of Laravel < 5.2, instead of make:command, you'll need to use make:console.

This should create a QuizStart class in the /app/console/commands directory with App\Console\Commands namespace.

Finally, our command is not registered, therefore we need to add it into our /app/console/Kernel.php file in the $commands array (provide the class path and name):

protected $commands = [
    // Commands\Inspire::class,
    'App\Console\Commands\QuizStart'
];

 

Use php artisan cache:clear to clear the cache and try executing your command with the previous given name:

php artisan quiz:start

 COPY SNIPPET

As expected, this command should do nothing, now you only need to learn how to deal with the command.

Structure of a command

To customize the name of your command and description, change the name directly in the class and all the logic of the command will be stored in the handle function.

<?php
#/App/Console/Commands/QuizStart.php
namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * 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()
    {
        //
    }
}

 

Print text

To send output to the console, you can choose between the following method : line, info, comment, question and error methods. Each of these methods will use appropriate ANSI colors for their purpose.

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->line("Some text");
    $this->info("Hey, watch this !");
    $this->comment("Just a comment passing by");
    $this->question("Why did you do that?");
    $this->error("Ops, that should not happen.");
}

 

Command input : arguments and options

Expect arguments and options in the command

If you don't set which parameters or options expects your function, your command will be unable to work, even if you execute it with parameters.

In Laravel, in the signature property (command name) is where we define our arguments and options, directly in the string (unlike older versions of Laravel) :

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'quiz:start {user} {age} {--difficulty=} {--istest=}';

 

The arguments are registered in our commannd with the simple syntax of {argumentName} and the options as {--optionName=}. so now we don't need to create the get options and get arguments methods in our class.

It's syntax is very simple to understand, basically these are all the ways to use arguments and options in our command (if you want more details, please read the docs):

  • Argumentquiz:start {argument}.
  • Optional Argument (note the question mark next to the argument name): quiz:start {argument?}.
  • Argument with default valuequiz:start {argument=defaultValue}.
  • Boolean Optionquiz:start --myOption.
  • Option with Valuequiz:start --myOption=.
  • Option with Value and Defaultquiz:start --myOption=12.

Retrieve arguments and options values

If your command needs some values to work (parameters), you'll need to access these values to use them in your command. To achieve this task, you can use the argument and option methods :

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    // Get single Parameters
    $username = $this->argument('user');
    $difficulty = $this->option('difficulty');

    // Get all
    $arguments = $this->arguments();
    $options = $this->options();

    // Stop execution and ask a question 
    $answer = $this->ask('What is your name?');

    // Ask for sensitive information
    $password = $this->secret('What is the password?');

    // Choices
    $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);

    // Confirmation

    if ($this->confirm('Is '.$name.' correct, do you wish to continue? [y|N]')) {
        //
    }
}

 

Example

The following function will create an interactive quiz in the console and you need to answer all of them. Once the quiz has been filled out, it will show the answers that you typed.

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $difficulty =  $this->option('difficulty');

    if(!$difficulty){
        $difficulty = 'easy';
    }

    $this->line('Welcome '.$this->argument('user').", starting test in difficulty : ". $difficulty);

    $questions = [
        'easy' => [
            'How old are you ?', "What is the name of your mother?",
            'Do you have 3 parents ?','Do you like Javascript?',
            'Do you know what is a JS promise?'
        ],
        'hard' => [
            'Why the sky is blue?', "Can a kangaroo jump higher than a house?",
            'Do you think i am a bad father?','why the dinosaurs disappeared?',
            "why don't whales have gills?"
        ]
    ];

    $questionsToAsk = $questions[$difficulty];
    $answers = [];

    foreach($questionsToAsk as $question){
        $answer = $this->ask($question);
        array_push($answers,$answer);
    }

    $this->info("Thanks for do the quiz in the console, your answers : ");

    for($i = 0;$i <= (count($questionsToAsk) -1 );$i++){
        $this->line(($i + 1).') '. $answers[$i]);
    }
}

 COPY SNIPPET

Laravel artisan quiz

Executing a command from a controller or route

Obviously, as we used the ask method, it shouldn't work however for other methods you would be able to execute the command using :

$exitCode = Artisan::call('quiz:start', [
    'user' => 'Carlos', '--difficulty' => 'hard'
]);

 

 

https://laravel-docs-pt-br.readthedocs.io/en/5.0/commands/

https://ourcodeworld.com/articles/read/248/how-to-create-a-custom-console-command-artisan-for-laravel-5-3


0

Share

Donate to Site


About Author

Renato

Developer

Add a Comment
Comments 1 Comments
  • Renato de Oliveira Lucena
    Renato de Oliveira Lucena - há 3 anos
    https://mattstauffer.com/blog/advanced-input-output-with-artisan-commands-tables-and-progress-bars-in-laravel-5.1/

Blog Search


Categories

OUTROS (15) Variados (109) PHP (130) Laravel (157) Black Hat (3) front-end (28) linux (111) postgresql (39) Docker (25) rest (5) soap (1) webservice (6) October (1) CMS (2) node (7) backend (13) ubuntu (54) devops (25) nodejs (5) npm (2) nvm (1) git (8) firefox (1) react (6) reactnative (5) collections (1) javascript (6) reactjs (7) yarn (0) adb (1) Solid (2) blade (3) models (1) controllers (0) log (0) html (2) hardware (3) aws (14) Transcribe (2) transcription (1) google (4) ibm (1) nuance (1) PHP Swoole (5) mysql (31) macox (4) flutter (1) symfony (1) cor (1) colors (2) homeOffice (2) jobs (3) imagick (2) ec2 (1) sw (1) websocket (1) markdown (1) ckeditor (1) tecnologia (14) faceapp (1) eloquent (14) query (4) sql (40) ddd (3) nginx (9) apache (4) certbot (1) lets-encrypt (3) debian (11) liquid (1) magento (2) ruby (1) LETSENCRYPT (1) Fibonacci (1) wine (1) transaction (1) pendrive (1) boot (1) usb (1) prf (1) policia (2) federal (1) lucena (1) mongodb (4) paypal (1) payment (1) zend (1) vim (4) ciencia (6) js (1) nosql (1) java (1) JasperReports (1) phpjasper (1) covid19 (1) saude (1) athena (1) cinnamon (1) phpunit (2) binaural (1) mysqli (3) database (42) windows (6) vala (1) json (2) oracle (1) mariadb (4) dev (12) webdev (24) s3 (4) storage (1) kitematic (1) gnome (2) web (2) intel (3) piada (1) cron (2) dba (18) lumen (1) ffmpeg (2) android (2) aplicativo (1) fedora (2) shell (4) bash (3) script (3) lider (1) htm (1) csv (1) dropbox (1) db (3) combustivel (2) haru (1) presenter (1) gasolina (1) MeioAmbiente (1) Grunt (1) biologia (1) programming (22) performance (3) brain (1) smartphones (1) telefonia (1) privacidade (1) opensource (3) microg (1) iode (1) ssh (3) zsh (2) terminal (3) dracula (1) spaceship (1) mac (2) idiomas (1) laptop (2) developer (37) api (4) data (1) matematica (1) seguranca (2) 100DaysOfCode (9) hotfix (1) documentation (1) laravelphp (10) RabbitMQ (1) Elasticsearch (1) redis (2) Raspberry (4) Padrao de design (4) JQuery (1) angularjs (4) Dicas (37) Kubernetes (2) vscode (2) backup (1) angular (3) servers (2) pipelines (1) AppSec (1) DevSecOps (4) rust (1) RustLang (1) Mozilla (1) algoritimo (1) sqlite (1) Passport (1) jwt (4) security (2) translate (1) kube (1) iot (1) politica (2) bolsonaro (1) flow (1) podcast (1) Brasil (1) containers (2) traefik (1) networking (1) host (1) POO (2) microservices (2) bug (1) cqrs (1) arquitetura (2) Architecture (3) sail (3) militar (1) artigo (1) economia (1) forcas armadas (1) ffaa (1) autenticacao (1) autorizacao (2) authentication (4) authorization (2) NoCookies (1) wsl (4) memcached (1) macos (2) unix (2) kali-linux (1) linux-tools (5) apple (1) noticias (2) composer (1) rancher (1) k8s (1) escopos (1) orm (1) jenkins (4) github (5) gitlab (3) queue (1) Passwordless (1) sonarqube (1) phpswoole (1) laraveloctane (1) Swoole (1) Swoole (1) octane (1) Structurizr (1) Diagramas (1) c4 (1) c4-models (1) compactar (1) compression (1) messaging (1) restfull (1) eventdrive (1) services (1) http (1) Monolith (1) microservice (1) historia (1) educacao (1) cavalotroia (1) OOD (0) odd (1) chatgpt (1) openai (3) vicuna (1) llama (1) gpt (1) transformers (1) pytorch (1) tensorflow (1) akitando (1) ia (1) nvidia (1) agi (1) guard (1) multiple_authen (2) rpi (1) auth (1) auth (1) livros (2) ElonMusk (2) Oh My Zsh (1) Manjaro (1) BigLinux (2) ArchLinux (1) Migration (1) Error (1) Monitor (1) Filament (1) LaravelFilament (1) replication (1) phpfpm (1) cache (1) vpn (1) l2tp (1) zorin-os (1) optimization (1) scheduling (1) monitoring (2) linkedin (1) community (1) inteligencia-artificial (2) wsl2 (1) maps (1) API_KEY_GOOGLE_MAPS (1) repmgr (1) altadisponibilidade (1) banco (1) modelagemdedados (1) inteligenciadedados (4) governancadedados (1) bancodedados (2) Observability (1) picpay (1) ecommerce (1)

New Articles



Get Latest Updates by Email