DEV Community

Cover image for Building CLI Commands in Laravel Artisan
Abodh Kumar for AddWeb Solution Pvt Ltd

Posted on • Edited on

Building CLI Commands in Laravel Artisan

Don’t build features only for users - build commands for systems. That’s where real automation begins. – ‘Taylor Otwell’

Laravel Artisan is a powerful command-line interface (CLI) that comes built-in with the framework. It helps developers automate tasks, generate boilerplate code, schedule background jobs, interact with the application, and build custom CLI tools tailored to business needs. Creating your own Artisan command enables you to extend Laravel beyond HTTP and build highly efficient terminal utilities.

Key Takeaways:

  • Laravel Artisan CLI automates business and DevOps tasks.
  • Supports flexible arguments and options for configurable commands.
  • Enables interactive terminal UX with prompts and choices.
  • Provides full access to models and database inside CLI.
  • Allows async execution by dispatching background jobs.
  • Runs recurring tasks reliably using Laravel Scheduler.

Table of Index

  1. Introduction to Artisan CLI
  2. Why Build Custom CLI Commands?
  3. Generating an Artisan Command
  4. Understanding Command Structure
  5. Accepting Arguments and Options
  6. Writing Interactive CLI Commands
  7. Using Services, Models, and DB in CLI
  8. Command Output Formatting
  9. Registering Commands
  10. Best Practices
  11. FAQ
  12. Interesting Facts
  13. Conclusion

1. Introduction to Artisan CLI

Artisan is Laravel’s terminal assistant. Whether you're running migrations, clearing cache, managing queues, or scaffolding code, Artisan improves developer productivity. It also acts as a foundation for building custom automation scripts.

2. Why Build Custom CLI Commands?

Custom CLI commands are useful when:

  • You want to automate repetitive tasks (e.g., data imports, cleanup, reports)
  • You need to trigger jobs or services manually
  • You want to build internal tools for DevOps, monitoring, or administration
  • You want terminal-based workflows without exposing HTTP endpoints
  • You need scheduled background processes via CLI

3. Generating an Artisan Command

Laravel provides a simple command generator:

   php artisan make:command SendDailyReport

Enter fullscreen mode Exit fullscreen mode

This creates a new file under:

   app/Console/Commands/SendDailyReport.php

Enter fullscreen mode Exit fullscreen mode

If HTTP is Laravel’s voice, Artisan is its discipline - quiet, consistent, and unstoppable. – ‘Taylor Otwell’

4. Understanding Command Structure

A generated command contains key properties:

protected $signature = 'report:daily';
   protected $description = 'Send daily system report to admin';
Enter fullscreen mode Exit fullscreen mode

And a handle() method where logic lives:

 public function handle() {
      $this->info("Daily report sent successfully!");
   }
Enter fullscreen mode Exit fullscreen mode

5. Accepting Arguments and Options

With arguments:

   protected $signature = 'user:create {name} {email}';

Enter fullscreen mode Exit fullscreen mode

Usage:

   php artisan user:create "Alex" "alex@example.com"

Enter fullscreen mode Exit fullscreen mode

Accessing in code:

 $name = $this->argument('name');
   $email = $this->argument('email');

Enter fullscreen mode Exit fullscreen mode

With options:

   protected $signature = 'user:create {name} {email} {--admin}';

Enter fullscreen mode Exit fullscreen mode

Usage:

   php artisan user:create "Alex" "alex@example.com" --admin

Enter fullscreen mode Exit fullscreen mode

Check in code:

if ($this->option('admin')) {
      $this->warn("Admin user will be created");
    }
Enter fullscreen mode Exit fullscreen mode

6. Writing Interactive CLI Commands

You can prompt users inside the terminal:

   $name = $this->ask("Enter user name");
   $password = $this->secret("Enter password");
   if ($this->confirm("Do you want to continue?")) {
      $this->info("User confirmed");
   }
Enter fullscreen mode Exit fullscreen mode

Laravel also supports choice inputs:

   $role = $this->choice("Select Role", ["User", "Manager", "Admin"], 0);

Enter fullscreen mode Exit fullscreen mode

Artisan is not just a CLI - it’s Laravel’s automation engine, transforming manual effort into repeatable terminal intelligence.

7. Using Services, Models, and DB in CLI

You can access anything from your Laravel app:

use App\Models\User;
   use Illuminate\Support\Facades\DB;

   public function handle() {
      $users = User::count();
      $logs = DB::table('activity_logs')->latest()->limit(5)->get();
      $this->info("Total Users: " . $users);
      $this->table(["ID","Log"], $logs->map(fn($l)=>[$l->id,$l->log]));
   }
Enter fullscreen mode Exit fullscreen mode

You can also dispatch jobs:

SendDailyReportJob::dispatch();
   $this->info("Job dispatched!");
Enter fullscreen mode Exit fullscreen mode

8. Command Output Formatting

Laravel provides rich CLI output helpers:

Example table output:

 $this->table(
      ["Name", "Email"],
      [["Abodh", "abodh@example.com"], ["Kumar", "k@example.com"]]
   );

Enter fullscreen mode Exit fullscreen mode

9. Registering Commands

Laravel auto-loads commands placed in:

   app/Console/Commands
Enter fullscreen mode Exit fullscreen mode

But you can manually register in Kernel.php:

protected $commands = [
      Commands\SendDailyReport::class,
   ];
Enter fullscreen mode Exit fullscreen mode

10. Best Practices

  • Keep commands single-purpose
  • Use service classes instead of heavy logic inside handle()
  • Add meaningful signature namespaces (module:task)
  • Log command activities for debugging
  • Make commands interactive when needed
  • Use scheduling instead of manual cron jobs

Write commands that matter. Let Artisan execute them at scale.

11. FAQ

1. What is Laravel Artisan?
Ans:- Artisan is Laravel’s built-in CLI tool for running framework commands and custom terminal automation scripts.

2. Where are custom Artisan commands stored?
Ans:- Inside: app/Console/Commands/

3. How do I create a new Artisan command?
Ans:- Run: php artisan make:command CommandName

4. What is the purpose of the signature property?
Ans:- It defines how the command is called in the terminal, including arguments and options.

5. Can Artisan commands interact with the database?
Ans:- Yes, you can use Eloquent models, Query Builder, or DB facade inside CLI commands.

6. What are command options in Artisan?
Ans:- Flags that modify behavior, e.g., --force, --admin, defined in the command signature.

7. Does CLI support user input interaction?
Ans:- Yes, using ask(), confirm(), choice(), secret() methods.

12. Interesting Facts & Insights:

13. Conclusion

Building CLI commands in Laravel Artisan unlocks a new layer of automation and control. It empowers developers to create reusable internal tools, execute background logic safely without HTTP exposure, and streamline workflows for both development and production environments.
Laravel CLI commands are not just scripts — they are first-class citizens of your application, capable of interacting with your services, database, jobs, and business logic with the same power as controllers or API endpoints.

About the Author: Abodh is a PHP and Laravel Developer at AddWeb Solution, skilled in MySQL, REST APIs, JavaScript, Git, and Docker for building robust web applications.

Top comments (0)