LaraflareDocsPackages13.x

Docs / Digging Deeper / Artisan Console

Artisan Console

Introduction

Artisan is the command line interface included with Laraflare. Artisan exists at the root of your application as the artisan script and provides a number of helpful commands you can use while building your application. To view a list of all available Artisan commands, you may use the list command:

npx artisan list

Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with help:

npx artisan help migrate

Note

Laraflare has no Tinker REPL. To try code against your application, write a closure command or a test.

Writing Commands

In addition to the commands provided with Artisan, you may build your own custom commands. Commands are typically stored in the app/Console/Commands directory; however, you are free to choose your own storage location as long as you instruct Laraflare to scan other directories for Artisan commands.

Generating Commands

To create a new command, you may use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don't worry if this directory does not exist in your application - it will be created the first time you run the make:command Artisan command:

npx artisan make:command SendEmails

Command Structure

After generating your command, you should define the command's signature and description properties. The signature property also allows you to define your command's input expectations. The handle method will be called when your command is executed. You may place your command logic in this method.

Let's take a look at an example command:

import { Command } from '@laraflare/framework';
import { User } from '../../Models/User';
import { DripEmailer } from '../../Support/DripEmailer';

export class SendEmails extends Command {
  /**
   * The name and signature of the console command.
   */
  protected override signature = 'mail:send {user}';

  /**
   * The console command description.
   */
  protected override description = 'Send a marketing email to a user';

  /**
   * Execute the console command.
   */
  async handle(): Promise<void> {
    const drip = new DripEmailer();

    await drip.send(await User.find(this.argument('user')));
  }
}

Note

For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example above, note that we use a service class to do the "heavy lifting" of sending the emails.

Exit Codes

If nothing is returned from the handle method and the command executes successfully, the command will exit with a 0 exit code, indicating success. However, the handle method may optionally return an integer to manually specify the command's exit code:

this.error('Something went wrong.');

return 1;

If you would like to "fail" the command from any method within the command, you may utilize the fail method. The fail method will immediately terminate execution of the command and return an exit code of 1:

this.fail('Something went wrong.');

Closure Commands

Closure-based commands provide an alternative to defining console commands as classes. In the same way that route closures are an alternative to controllers, think of command closures as an alternative to command classes.

Even though the routes/console.ts file does not define HTTP routes, it defines console-based entry points (routes) into your application. Within this file, you may define all of your closure-based console commands using the Artisan.command method. The command method accepts two arguments: the command signature and a closure which receives the command's arguments and options:

import { Artisan, type ClosureCommand } from '@laraflare/framework';

Artisan.command('mail:send {user}', async function (this: ClosureCommand, user: string) {
  this.info(`Sending email to: ${user}!`);
});

The closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.

Closure Command Descriptions

When defining a closure-based command, you may use the purpose method to add a description to the command. This description will be displayed when you run the npx artisan list or npx artisan help commands:

Artisan.command('mail:send {user}', async function (this: ClosureCommand, user: string) {
  // ...
}).purpose('Send a marketing email to a user');

Isolatable Commands

Warning

To utilize this feature, your application must be using the memcached, redis, dynamodb, database, file, or array cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.

Sometimes you may wish to ensure that only one instance of a command can run at a time. To accomplish this, you may add the Isolatable contract to your command class by extending Isolatable(Command):

import { Command, Isolatable } from '@laraflare/framework';

export class SendEmails extends Isolatable(Command) {
  // ...
}

When you mark a command as Isolatable, Laraflare automatically makes the --isolated option available for the command without needing to explicitly define it in the command's options. When the command is invoked with that option, Laraflare will ensure that no other instances of that command are already running. Laraflare accomplishes this by attempting to acquire an atomic lock using your application's default cache driver. If other instances of the command are running, the command will not execute; however, the command will still exit with a successful exit status code:

npx artisan mail:send 1 --isolated

If you would like to specify the exit status code that the command should return if it is not able to execute, you may provide the desired status code via the isolated option:

npx artisan mail:send 1 --isolated=12

Lock ID

By default, Laraflare will use the command's name to generate the string key that is used to acquire the atomic lock in your application's cache. However, you may customize this key by defining an isolatableId method on your Artisan command class, allowing you to integrate the command's arguments or options into the key:

/**
 * Get the isolatable ID for the command.
 */
isolatableId(): string {
  return this.argument('user') as string;
}

Lock Expiration Time

By default, isolation locks expire after the command is finished. Or, if the command is interrupted and unable to finish, the lock will expire after one hour. However, you may adjust the lock expiration time by defining an isolationLockExpiresAt method on your command, which returns a Date or a number of seconds:

/**
 * Determine when an isolation lock expires for the command.
 */
isolationLockExpiresAt(): number {
  return 5 * 60;
}

Defining Input Expectations

When writing console commands, it is common to gather input from the user through arguments or options. Laraflare makes it very convenient to define the input you expect from the user using the signature property on your commands. The signature property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.

Arguments

All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user:

/**
 * The name and signature of the console command.
 */
protected override signature = 'mail:send {user}';

You may also make arguments optional or define default values for arguments:

// Optional argument...
'mail:send {user?}'

// Optional argument with default value...
'mail:send {user=foo}'

Options

Options, like arguments, are another form of user input. Options are prefixed by two hyphens (--) when they are provided via the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option:

protected override signature = 'mail:send {user} {--queue}';

In this example, the --queue switch may be specified when calling the Artisan command. If the --queue switch is passed, the value of the option will be true. Otherwise, the value will be false:

npx artisan mail:send 1 --queue

Options With Values

Next, let's take a look at an option that expects a value. If the user must specify a value for an option, you should suffix the option name with a = sign:

protected override signature = 'mail:send {user} {--queue=}';

In this example, the user may pass a value for the option like so. If the option is not specified when invoking the command, its value will be null:

npx artisan mail:send 1 --queue=default

You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:

'mail:send {user} {--queue=default}'

Option Shortcuts

To assign a shortcut when defining an option, you may specify it before the option name and use the | character as a delimiter to separate the shortcut from the full option name:

'mail:send {user} {--Q|queue=}'

When invoking the command on your terminal, option shortcuts should be prefixed with a single hyphen and no = character should be included when specifying a value for the option:

npx artisan mail:send 1 -Qdefault

Input Arrays

If you would like to define arguments or options to expect multiple input values, you may use the * character. First, let's take a look at an example that specifies such an argument:

'mail:send {user*}'

When running this command, the user arguments may be passed in order to the command line. For example, the following command will set the value of user to an array with 1 and 2 as its values:

npx artisan mail:send 1 2

This * character can be combined with an optional argument definition to allow zero or more instances of an argument:

'mail:send {user?*}'

Option Arrays

When defining an option that expects multiple input values, each option value passed to the command should be prefixed with the option name:

'mail:send {--id=*}'

Such a command may be invoked by passing multiple --id arguments:

npx artisan mail:send --id=1 --id=2

Input Descriptions

You may assign descriptions to input arguments and options by separating the argument name from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:

protected override signature = `mail:send
                        {user : The ID of the user}
                        {--queue : Whether the job should be queued}`;

Prompting for Missing Input

If your command contains required arguments, the user will receive an error message when they are not provided. Alternatively, you may configure your command to automatically prompt the user when required arguments are missing by adding the PromptsForMissingInput contract:

import { Command, PromptsForMissingInput } from '@laraflare/framework';

export class SendEmails extends PromptsForMissingInput(Command) {
  /**
   * The name and signature of the console command.
   */
  protected override signature = 'mail:send {user}';

  // ...
}

If Laraflare needs to gather a required argument from the user, it will automatically ask the user for the argument by intelligently phrasing the question using either the argument name or description. If you wish to customize the question used to gather the required argument, you may implement the promptForMissingArgumentsUsing method, returning an object of questions keyed by the argument names:

/**
 * Prompt for missing input arguments using the returned questions.
 */
protected promptForMissingArgumentsUsing(): Record<string, string> {
  return {
    user: 'Which user ID should receive the mail?',
  };
}

You may also provide placeholder text by using a tuple containing the question and placeholder:

return {
  user: ['Which user ID should receive the mail?', 'E.g. 123'],
};

If you wish to prompt the user to select or enter options, you may include prompts in your command's handle method. However, if you only wish to prompt the user when they have also been automatically prompted for missing arguments, then you may implement the afterPromptingForMissingArguments method:

/**
 * Perform actions after the user was prompted for missing arguments.
 */
protected async afterPromptingForMissingArguments(input: InputInterface, output: OutputInterface): Promise<void> {
  input.setOption('queue', await this.confirm('Would you like to queue the mail?', Boolean(this.option('queue'))));
}

Command I/O

Retrieving Input

While your command is executing, you will likely need to access the values for the arguments and options accepted by your command. To do so, you may use the argument and option methods. If an argument or option does not exist, null will be returned:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  const userId = this.argument('user');
}

If you need to retrieve all of the arguments as an object, call the arguments method:

const args = this.arguments();

Options may be retrieved just as easily as arguments using the option method. To retrieve all of the options as an object, call the options method:

// Retrieve a specific option...
const queueName = this.option('queue');

// Retrieve all options as an object...
const options = this.options();

You may use the input method to retrieve a command's arguments and options as a CommandInputData instance, which provides the same typed accessors that are available on HTTP requests and other data containers:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  const input = this.input();

  // ...
}

The input method may also be used to retrieve a single input value from either the arguments or options:

const queue = this.input('queue', 'default');

Prompting for Input

In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user's input back to your command:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  const name = await this.ask('What is your name?');

  // ...
}

The ask method also accepts an optional second argument which specifies the default value that should be returned if no user input is provided:

const name = await this.ask('What is your name?', 'Taylor');

The secret method is similar to ask, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as passwords:

const password = await this.secret('What is the password?');

Asking for Confirmation

If you need to ask the user for a simple "yes or no" confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y or yes in response to the prompt, the method will return true.

if (await this.confirm('Do you wish to continue?')) {
  // ...
}

If necessary, you may specify that the confirmation prompt should return true by default by passing true as the second argument to the confirm method:

if (await this.confirm('Do you wish to continue?', true)) {
  // ...
}

Auto-Completion

The anticipate method can be used to provide auto-completion for possible choices. The user can still provide any answer, regardless of the auto-completion hints:

const name = await this.anticipate('What is your name?', ['Taylor', 'Dayle']);

Alternatively, you may pass a closure as the second argument to the anticipate method. The closure will be called each time the user types an input character. The closure should accept a string parameter containing the user's input so far, and return an array of options for auto-completion:

const name = await this.anticipate('What is your name?', (input: string) => {
  return ['Taylor', 'Dayle'].filter((name) => name.startsWith(input));
});

Multiple Choice Questions

If you need to give the user a predefined set of choices when asking a question, you may use the choice method. You may set the array index of the default value to be returned if no option is chosen by passing the index as the third argument to the method:

const name = await this.choice(
  'What is your name?',
  ['Taylor', 'Dayle'],
  defaultIndex,
);

In addition, the choice method accepts optional fourth and fifth arguments for determining the maximum number of attempts to select a valid response and whether multiple selections are permitted:

const name = await this.choice(
  'What is your name?',
  ['Taylor', 'Dayle'],
  defaultIndex,
  null, // maxAttempts
  false, // allowMultipleSelections
);

Writing Output

To send output to the console, you may use the line, newLine, info, comment, question, warn, alert, and error methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the info method will display in the console as green colored text:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  // ...

  this.info('The command was successful!');
}

To display an error message, use the error method. Error message text is typically displayed in red:

this.error('Something went wrong!');

You may use the line method to display plain, uncolored text:

this.line('Display this on the screen');

You may use the newLine method to display a blank line:

// Write a single blank line...
this.newLine();

// Write three blank lines...
this.newLine(3);

Tables

The table method makes it easy to correctly format multiple rows / columns of data. All you need to do is provide the column names and the data for the table and Laraflare will automatically calculate the appropriate width and height of the table for you:

import { User } from '../../Models/User';

this.table(
  ['Name', 'Email'],
  (await User.all(['name', 'email'])).toArray(),
);

Progress Bars

For long running tasks, it can be helpful to show a progress bar that informs users how complete the task is. Using the withProgressBar method, Laraflare will display a progress bar and advance its progress for each iteration over a given iterable value:

const users = await User.all();

await this.withProgressBar(users, async (user) => {
  await this.performTask(user);
});

Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar after processing each item:

const users = (await User.all()).all();

const bar = this.output.createProgressBar(users.length);

bar.start();

for (const user of users) {
  await this.performTask(user);

  bar.advance();
}

bar.finish();

Registering Commands

By default, Laraflare automatically registers all commands within the app/Console/Commands directory. However, you can instruct Laraflare to scan other directories for Artisan commands using the withCommands method in your application's bootstrap/app.ts file:

.withCommands([
  'app/Domain/Orders/Commands',
])

If necessary, you may also manually register commands by providing the command's class to the withCommands method:

import { SendEmails } from '../app/Domain/Orders/Commands/SendEmails';

.withCommands([
  SendEmails,
])

Note

The skeleton's bootstrap/app.ts loads the closure commands in routes/console.ts through withRouting({ commands }). A Worker has no folder to scan, so the commands in app/Console/Commands are found by the artisan program on your machine.

Programmatically Executing Commands

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to execute an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts either the command's signature name or class as its first argument, and an object of command parameters as the second argument. The exit code will be returned:

import { Artisan, Route } from '@laraflare/framework';

Route.post('/user/{user}/mail', async (request, user: string) => {
  const exitCode = await Artisan.call('mail:send', {
    user, '--queue': 'default',
  });

  // ...
});

Alternatively, you may pass the entire Artisan command to the call method as a string:

await Artisan.call('mail:send 1 --queue=default');

Note

Artisan commands that read files or run on your machine, such as migrate or make:*, belong to the artisan program. A deployed Worker has no filesystem, so call only commands that work with the database, cache or queue.

Passing Array Values

If your command defines an option that accepts an array, you may pass an array of values to that option:

Route.post('/mail', async () => {
  const exitCode = await Artisan.call('mail:send', {
    '--id': [5, 13],
  });
});

Passing Boolean Values

If you need to specify the value of an option that does not accept string values, such as the --force flag on the migrate:refresh command, you should pass true or false as the value of the option:

const exitCode = await Artisan.call('migrate:refresh', {
  '--force': true,
});

Queueing Artisan Commands

Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:

Route.post('/user/{user}/mail', async (request, user: string) => {
  Artisan.queue('mail:send', {
    user, '--queue': 'default',
  });

  // ...
});

Using the onConnection and onQueue methods, you may specify the connection or queue the Artisan command should be dispatched to:

Artisan.queue('mail:send', {
  user: 1, '--queue': 'default',
}).onConnection('redis').onQueue('commands');

Calling Commands From Other Commands

Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call method. This call method accepts the command name and an object of command arguments / options:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  await this.call('mail:send', {
    user: 1, '--queue': 'default',
  });

  // ...
}

If you would like to call another console command and suppress all of its output, you may use the callSilently method. The callSilently method has the same signature as the call method:

await this.callSilently('mail:send', {
  user: 1, '--queue': 'default',
});

Signal Handling

As you may know, operating systems allow signals to be sent to running processes. For example, the SIGTERM signal is how operating systems ask a program to terminate gracefully. If you wish to listen for signals in your Artisan console commands and execute code when they occur, you may use the trap method:

/**
 * Execute the console command.
 */
async handle(): Promise<void> {
  this.trap('SIGTERM', () => this.shouldKeepRunning = false);

  while (this.shouldKeepRunning) {
    // ...
  }
}

To listen for multiple signals at once, you may provide an array of signals to the trap method:

this.trap(['SIGTERM', 'SIGQUIT'], (signal: string) => {
  this.shouldKeepRunning = false;

  console.log(signal); // SIGTERM / SIGQUIT
});

The Dev Command

The dev Artisan command starts all of the processes needed for local development in a single terminal window. By default, it concurrently runs the development server, a queue listener, and Vite asset compilation (plus log tailing when Pail is installed):

npx artisan dev

Each process is labeled and color-coded so you can easily distinguish between them. If a process crashes, it will be restarted automatically.

The default processes are:

Name Command
server artisan serve
queue artisan queue:listen --tries=1 --timeout=0
logs artisan pail --timeout=0 (only when Pail is installed)
vite npm run dev (only when the app has a package.json)

Note

The vite process automatically detects your Node package manager (npm, pnpm, Yarn, or Bun) and uses the appropriate run command.

Customizing Dev Processes

You may customize the processes that the dev command runs by using the DevCommands class, typically within the boot method of your application's AppServiceProvider. The register method accepts a command string and an optional name:

/**
 * Bootstrap any application services.
 */
boot(): void {
  DevCommands.register('some-command --flag', 'my-process');
}

When registering an Artisan command, you may use the artisan method which automatically prefixes the command with the artisan program:

DevCommands.artisan('horizon', 'horizon');

Likewise, the node method prefixes the command with your detected package manager's run command (e.g. npm run), and the nodeExec method prefixes the command with the package manager's exec command (e.g. npx):

DevCommands.node('storybook', 'storybook');

DevCommands.nodeExec('tailwindcss -i resources/css/app.css -o public/css/app.css --watch', 'tailwind');

If you register a process with the same name as a default process, your process will replace the default. For example, you may customize the server process to use a different port:

DevCommands.artisan('serve --host=localhost --port=9000', 'server');

You may also customize the color of a process label in your terminal. The available color methods are blue, purple, pink, orange, green, and yellow. You may also pass a custom hex color to the color method:

DevCommands.register('my-command', 'my-process').green();

DevCommands.register('my-command', 'my-process').color('#ff6347');

To see all registered dev processes without starting them, use the dev:list command:

npx artisan dev:list

Restarting Failed Processes

If a process crashes, Laraflare will restart it after a short delay before marking it as failed. You may disable this behavior for your entire application using the disableAutoRestart method:

DevCommands.disableAutoRestart();

Filtering Dev Processes

You may instruct the dev command to only run specific processes when it is invoked using the only method. Similarly, you may exclude specific processes using the except method:

// Only run the server and vite processes...
DevCommands.only('server', 'vite');

// Run all processes except the queue worker...
DevCommands.except('queue');

You may exclude commands registered by packages or Laraflare's default commands using the withoutVendorCommands and withoutDefaultCommands methods:

DevCommands.withoutVendorCommands();

DevCommands.withoutDefaultCommands();

Stub Customization

The Artisan console's make commands are used to create a variety of classes, such as controllers, jobs, migrations, and tests. These classes are generated using "stub" files that are populated with values based on your input. However, you may want to make small changes to files generated by Artisan. To accomplish this, you may use the stub:publish command to publish the most common stubs to your application so that you can customize them:

npx artisan stub:publish

The published stubs will be located within a stubs directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan's make commands.

Events

Artisan dispatches three events when running commands: ArtisanStarting, CommandStarting, and CommandFinished, all exported from @laraflare/framework. The ArtisanStarting event is dispatched immediately when Artisan starts running. Next, the CommandStarting event is dispatched immediately before a command runs. Finally, the CommandFinished event is dispatched once a command finishes executing.

Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.