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 Error pages in laravel

How to create a custom 404 page in Laravel 8 ?

December 28, 2021December 28, 2021

Laravel provides its inbuilt 404 error page and shows text 404 page not found but we want more customization and better ui for 404 page so in this article i will show yo to customize the 404 not found error page in laravel. This article will cover you to create…

Read More
Php Laravel whereHas

Laravel whereHas in eloquent Model Example

October 2, 2022March 16, 2024

In this blog post, we’ll take a look at Laravel whereHas in eloquent Model Example and advantages. whereHas method is an important part of the Eloquent ORM. It allows you to add a constraint to a relationship query. whereHas method can be used to filter records based on a relationship….

Read More
Php How to Get Only Soft Deleted Records in Laravel 9

How to Get Only Soft Deleted Records in Laravel 9 ?

June 20, 2022June 20, 2022

In this article we will learn to get only soft deleted records in Laravel. In our recent article Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 we learnt to delete the file without actually deleting from database and sometimes we want to show only that records…

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

  • 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 Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version