Getting Started

Summary: Laravel comes with a built-in command line interface, Artisan. It offers developers a lot of useful commands to sort out issues and boost the overall development process.

Creating a Custom Console Command in Laravel

Laravel comes with a built-in command line interface, Artisan. It offers developers a lot of useful commands to sort out issues and boost the overall development process. Developers use PHP Artisan to perform some important functional operations which include generating migrations, publishing package assets and many similar tasks.

Artisan allows us to add custom commands to serve frequent tasks. In this post, we will see how to create custom commands in Artisan.

Steps in creating Artisan Commands

First of all, check out the list of available built-in commands in Artisan

php artisan help

check the feature and argument of any command by

php help artisan <command name>

If not found then proceed with the following steps to create a one

php artisan make:command <command name>

for instances, php artisan make:command SendEmails

Registering it in console

protected $commands = [

   // Commands\Inspire::class,

   'App\Console\Commands\SendEmails'

];

Command abstract

<?php

namespace App\Console\Commands;

use App\User;

use App\DripEmailer;

use Illuminate\Console\Command;

class SendEmails extends Command

{

   /**

    * The name and signature of the console command.

    *

    * @var string

    */

   protected $signature = 'email:send {user}';

   /**

    * The console command description.

    *

    * @var string

    */

   protected $description = 'Send drip e-mails to a user';

   /**

    * Create a new command instance.

    *

    * @return void

    */

   public function __construct()

   {

       parent::__construct();

   }

   /**

    * Execute the console command.

    *

    * @param  \App\DripEmailer  $drip

    * @return mixed

    */

   public function handle(DripEmailer $drip)

   {

       $drip->send(User::find($this->argument('user')));

   }

}

Arguments

protected $signature = 'email:send {user}';

“{arguments}” this is used to provide the arguments at the time of input

“{--arguments}” this is used to take when input is taking on the command line

Handle

 

public function handle()

{

   $this->line("Some text");

   $this->argument('user');

$this->error('error message');

}

Registering commands

protected function commands()

{

   $this->load(__DIR__.'/Commands');

   $this->load(__DIR__.'/MoreCommands');

}

This is how a custom command could be added to the console, that serves tasks according to need. Command function is abstractly shown here which can be toggled according to the specificity of the task.

 

Comments

Sign in to publish a comment

0 comments

Be the first to comment on this post.