Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 67 ยท Getting Started

Artisan and Custom Commands

Learn Laravel Artisan: list and help, make generators, tinker, and how to write your own command with a signature, arguments, options and output.

artisan is the small script at the root of every Laravel project. You run it with PHP, and it gives you a command line for the framework: create files, run migrations, clear caches, start workers, inspect routes and more. Learning Artisan early pays off, because most Laravel work is a mix of editing files and running a handful of php artisan commands.

You can also write your own commands, for jobs such as importing data, cleaning old records or sending a report. This lesson shows how to explore Artisan, how the generators save typing, how to write a command with a signature, arguments and options, and then builds a tiny command dispatcher in plain PHP so you can see how a signature turns into code that runs. Real Laravel code is read-only; the stand-in is runnable.

Exploring Artisan

From the project folder:

Terminal
php artisan list            # every command, grouped by topic
php artisan help migrate    # arguments and options for one command
php artisan about           # environment summary: PHP, Laravel, drivers
php artisan route:list      # all routes
php artisan --version

php artisan list is your map. Commands are grouped by a prefix before the colon: make: creates files, migrate: manages the database, cache: and config: manage caches, queue: and schedule: run background work. php artisan help <command> shows every argument and option, and adding --help to any command does the same.

Generators with make:

The make: commands create classes in the right folder, in the right namespace, with the right boilerplate. A few you will use constantly:

Terminal
php artisan make:model Post -mf      # model + migration + factory
php artisan make:controller PostController --resource
php artisan make:request StorePostRequest
php artisan make:middleware EnsureIsAdmin
php artisan make:migration add_slug_to_posts_table
php artisan make:command SendReport

Each command prints the path it created. Flags such as -m and --resource add companions or choose a template. Run php artisan make:model --help to see them all. Always prefer a generator over copying files by hand: it uses the same naming conventions that the rest of the framework expects. The generated classes also follow the layout you saw in The Project Structure, and Artisan creates folders such as app/Console/Commands on demand.

Tinker

Tinker is an interactive shell (a REPL) with your whole application loaded:

Terminal
php artisan tinker

Inside it you can run PHP and use your classes, as in App\Models\User::count() or config('app.name'). It is excellent for quick experiments and for checking what a query returns. You can also run a single expression without opening the shell:

Terminal
php artisan tinker --execute='echo config("app.name");'

Use single quotes around the whole expression so your shell does not interpret $ signs. Tinker runs against your real database, so be careful with writes and deletes.

Writing a command

Create a command with the generator:

Terminal
php artisan make:command SendReport

That creates app/Console/Commands/SendReport.php. Laravel discovers commands in that folder automatically, so there is nothing to register. Here is a complete example (read-only):

PHP
<?php

namespace App\Console\Commands;

use App\Models\Post;
use Illuminate\Console\Command;

class SendReport extends Command
{
    protected $signature = 'report:send {user : The user ID} {--dry-run : Do not send, only show} {--limit=5 : Number of posts}';

    protected $description = 'Send a post summary to a user';

    public function handle(): int
    {
        $userId = $this->argument('user');
        $limit = (int) $this->option('limit');

        $posts = Post::latest()->limit($limit)->get();

        $this->info("Preparing a report with {$posts->count()} posts for user {$userId}");

        if ($this->option('dry-run')) {
            $this->warn('Dry run: nothing sent.');

            return self::SUCCESS;
        }

        // send the mail here...

        $this->info('Done.');

        return self::SUCCESS;
    }
}

Run it like this:

Terminal
php artisan report:send 7
php artisan report:send 7 --limit=10 --dry-run

The signature

The $signature has a name followed by arguments and options in braces:

Syntax Meaning
Required argument
{user?} Optional argument
{user=1} Optional argument with a default
{user*} Array of arguments
{--dry-run} Boolean flag (false unless given)
{--limit=5} Option with a value and a default
`{--Q queue}`
{user : text} Description shown in help

Read values with $this->argument('user') and $this->option('limit'). Arguments are positional and usually identify the thing to work on; options are named and usually change behaviour.

Input and output helpers

Inside handle() the command has helpers for talking to the user:

  • Output: info(), line(), comment(), warn(), error(), and table($headers, $rows).
  • Questions: ask(), secret(), confirm() and choice(). Prompts that ask for input will wait forever in a scheduled or automated run, so only use them in commands people run by hand.
  • Progress: $this->withProgressBar($items, fn ($item) => ...).

Return an exit code: self::SUCCESS (0), self::FAILURE (1) or self::INVALID (2). Shell scripts and CI use it to know whether the command worked.

flowchart LR
    A["php artisan report:send 7 --dry-run"] --> B["Find command by name"]
    B --> C["Parse signature<br/>into arguments and options"]
    C --> D["handle()"]
    D --> E["Exit code"]

Artisan finds the command by name, parses the input against its signature, then calls handle().

Closure commands

For small jobs you do not need a class. routes/console.php can define commands with closures:

PHP
use Illuminate\Support\Facades\Artisan;

Artisan::command('inspire {name?}', function (?string $name = null) {
    $this->comment("Keep going, {$name}!");
})->purpose('Show a short message');

Closure commands are handy for quick utilities. For anything with real logic, prefer a class, which is easier to test. That file is also where you will define scheduled tasks later (Task Scheduling).

Try it: a mini command dispatcher

Laravel's console component parses a signature and fills in arguments and options. This stand-in does a simplified version: it understands , {arg?}, {arg=default}, {--flag} and {--opt=default}, and then runs the matching command. It is not Laravel's parser (which supports more), but it shows what happens between the text you type and handle().

PHP Parsing a signature and running a command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The exit codes follow the console convention: 0 means success, anything else means a problem. Real Artisan also suggests similar command names when you mistype one.

Output helpers are another part of a command. This second stand-in mimics info(), warn(), error() and table() with plain text, and shows why a command should return an exit code that reflects what happened:

PHP Output helpers and exit codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Good habits for commands

  • Keep handle() small. Move real logic into a service or action class that you can test and reuse from controllers and jobs (Architecture: Actions, Services and Clean Code).
  • Make destructive commands safe: add a --dry-run option or ask for confirm().
  • Return meaningful exit codes, and write errors with error() rather than info().
  • Name commands topic:action (report:send, cache:clear), like the built-in ones.
  • For recurring work, schedule the command rather than using many separate cron entries (Task Scheduling).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command shows every available Artisan command?

    php artisan list prints all commands, grouped by prefix. php artisan help <name> explains one command.
  2. 2. What does the signature report:send {user} {--limit=5} define?

    The name comes first, then arguments in braces. Names starting with -- are options, and =5 gives a default value.
  3. 3. How do you read an option named dry-run inside handle()?

    Options are read with option(), and arguments with argument().
  4. 4. What is php artisan tinker?

    Tinker is a REPL where you can run PHP and use your models and services against the real application.
  5. 5. What should a command's handle() method return?

    The exit code tells shells, CI and schedulers whether the command succeeded.

Summary

  • php artisan list and php artisan help <command> document everything; about and route:list inspect your app.
  • make: generators create classes in the right place; prefer them over manual copying.
  • php artisan tinker is an interactive shell for experiments; be careful, it uses your real database.
  • A command class defines a $signature (arguments and options), a $description and a handle() method that returns an exit code.
  • Use info(), warn(), error() and table() for output, and keep commands thin by moving logic into services.

Next: Routing Basics