Laravel: Make Custom Artisan Command

Link Copied To Clipboard !

how-to-make-custom-artisan-command-in-laravel Frameworks

Artisan is the command line interface that comes with laravel. It provides several useful commands for developing laravel application. It is driven by the powerful Symphony Console component.

Some of the common artisan commands are:-

  1. php artisan make:model (used to generate model)
  2. php artisan make:controller (used to generate controller)
  3. php artisan make:mail (used to generate mail)
  4. php artisan make:migration (used to generate database migration)
  5. php artisan make:event (used to generate event)
  6. php artisan make:command (used to generate artisan command) …etc.

We can use the 6th artisan command mentioned above to generate a custom command to fulfill our need.

How to make custom artisan command in laravel ?

  1. Generate a command using php artisan make:command TestCommand . Here TestCommand is our custom command.
  2. Open app/Console/Commands/TestCommand.php and set name and signature of command. Let’s say, we set the signature to test:execute .
  3. Write command logic inside handle function. The logic could be any business logic or operation like sending mails, notifications etc.
  4. Execute command. Considering our signature, we would run as php artisan test:execute .

The TestCommand.php file looks something like:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'The is description of test command';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //write what the command should do

    }
}

You can also pass arguments from command line and use them as required.

To know more about artisan commands, READ THE OFFICIAL DOCUMENTATION .

HAPPY CODING !


You May Also Like

News Letter