Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Create a Custom Artisan Command in LaravelHow to Create a Custom Artisan Command in Laravel

How to Create a Custom Artisan Command in Laravel ?

Aman Jain, May 19, 2022May 26, 2022

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'
    ]);
 
    //
});

Related

Php Laravel Laravel 9 artisancommandlaravel

Post navigation

Previous post
Next post

Related Posts

Php How to set timezone dynamically and globally in Laravel

How to get timezone select list in Laravel ?

September 21, 2022March 16, 2024

Hello Developers, In this article i will show you get timezone select list in Laravel. In a timezone based application we need to store the timezone of each client or user so we can show the correct time to them in their region. So in this article i will show…

Read More
Php Laravel max in eloquent query

Laravel max in eloquent query with example

January 23, 2022November 7, 2023

In this article we will learn to use aggregate function max in laravel eloquent and query builder. Laravel itself provide inbuilt method to max the columns like in MySQL or SQL based database we can do max of columns using max aggregate function. Laravel eloquent or query builder max method…

Read More
Laravel Laravel Components

Laravel artisan command to generate controllers, Model, Components and Migrations

August 22, 2021October 4, 2022

Laravel is robust framework of php which provides rapid development and security for low and high level projects. It have many features like Laravel Components, Validation, eloquent, migrations, artisnan security etc. Let’s have look artisan commands of laravel artisan. There is a command which gives you list of all available…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version