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 Custom helper function laravel

How to Create Custom Helper Functions in Laravel ?

December 21, 2021November 8, 2023

Sometimes in our application we want to create custom helper functions in laravel to use in our application, Laravel has so many helpers functions to work with strings, URL, email, array, debugging etc. so in this article i will show you to use custom helper functions in our Laravel application….

Read More
Php How to Get Current Url in Blade File Laravel

How to Get Current Url in Blade File Laravel ?

October 27, 2022March 16, 2024

Sometimes in our application we want to Get Current Url in Blade file Laravel because we want to add specific conditions to show the data on behalf of current url. It can be complete url, route name and query params too so that we can fetch the data accordingly and…

Read More
Php Laravel Rest Api OTP Login and Registration Without Password

Laravel Rest Api OTP Login and Registration Without Password

September 3, 2022March 16, 2024

Today most of the applications are using laravel rest api otp login and registration without password for ease of login and registration and also provides easy to login without remembering the password each time while login or register. In Laravel there is multiple ways to implement the login and registration…

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