Write your first laravel artisan command

According to the official introduction, artisan is defined as follows:

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. 

Such as data migration, email sending, creating components in laravel to improve development efficiency, etc.

For details, please see: https://learnku.com/docs/laravel/7.x/artisan/7480#introduction

Now let me show you how to create laravel artisan command:

STEP 1:

php artisan make:command DemoCommand

After execution, the following files will be generated in our project directory app/Console/Commands/DemoCommand.php, The content of the file is as follows:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DemoCommand 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 int
     */
    public function handle()
    {
        //
    }
}

STEP 2:

Then all we have to do is write the signature, description, and business logic of this command according to the specification. Below is an example:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'i am a demo';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // do something
        echo 'i am you first artisan.';
    }
}

STEP 3:

Now let’s run the above code to see the effect:

$ php artisan demo
i am you first artisan.

The above is just a very simple way to create commands, laravel also supports many ways to create artisan commands.

Combined with tinker can also create many interactive command, click here if you want to

Hope it can help you

RSS