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 Use Multiple Database Connection in Laravel

How to Use Multiple Database Connection in Laravel ?

August 16, 2022March 16, 2024

Laravel has ability to make use database connection and can be used any of connection at runtime. In this article i will show you to use multiple database connection in laravel from different servers and then use these connection in our application during the run time according to use of…

Read More
Php Laravel 10 Image Upload with Preview Example

Laravel 10 Image Upload with Preview Example

March 7, 2023March 16, 2024

In this blog post we will learn laravel image upload. Laravel 10 offers robust functionality for uploading and processing images, which is often a basic requirement for websites, ranging from setting up a profile picture to providing necessary documents. With Laravel 10, image uploads can be handled with enhanced security…

Read More
Php How to Delete Folder Recursively With Files in Laravel ?

How to Delete Folder Recursively With Files in Laravel ?

May 25, 2022May 26, 2022

File System are used to store the information and how to manage the structure, so to perform the file system based operations like Delete Folder Recursively With Files it uses Illuminate\Filesystem\Filesystem class in laravel. Laravel provides inbuilt library to access the file system and we can do multiple robust operations…

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

  • 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
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version