Skip to content

Console

Digging Deeper

Console

Introduction

Not every task in your application begins with an HTTP request. You may need to import a CSV file nightly, prune stale drafts, or repair data in production. Console commands handle these tasks directly from your application's binary, with full access to your configuration, services, and models.

Running your application binary with no command starts the HTTP server. Passing a command name executes that command instead. While you develop, run commands through the Laravel CLI, which compiles your application and then runs the command you name. It shows the compiler's output only when the build fails:

1laravel serve # serve the application
2laravel route:list # run a command
3laravel list # list every command
4laravel help route:list # show a command's help
1laravel serve # serve the application
2laravel route:list # run a command
3laravel list # list every command
4laravel help route:list # show a command's help

In production, you run the binary you built with the same arguments, such as ./app migrate --force.

Every command boots your application and executes inside an application context, so config, resolve, URL helpers, and your log channels work as they do in HTTP handlers. Because there is no incoming HTTP request, session and request helpers are not available.

Writing commands

Beyond the built-in commands, you can write your own. New applications place each command in its own file under src/console/. Define a command by annotating an async function with #[command] and its name. Its parameters define the command's input, parsed into typed values by clap. For example, this command publishes a draft post:

1use laravel::console::{Console, command};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[command("posts:publish")]
8pub async fn publish_post(
9 /// The ID of the post to publish.
10 id: i64,
11 /// Publish the post again if it's already published.
12 #[arg(long)]
13 force: bool,
14 console: &mut Console,
15) -> laravel::Result<()> {
16 let mut post = Post::find_or_fail(id).await?;
17 
18 if post.published_at.is_some() && !force {
19 console.info(format!("Post `{id}` is already published."));
20 
21 return Ok(());
22 }
23 
24 update!(post { published_at: laravel::now() }).await?;
25 
26 console.success(format!("Post `{id}` published."));
27 
28 Ok(())
29}
1use laravel::console::{Console, command};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[command("posts:publish")]
8pub async fn publish_post(
9 /// The ID of the post to publish.
10 id: i64,
11 /// Publish the post again if it's already published.
12 #[arg(long)]
13 force: bool,
14 console: &mut Console,
15) -> laravel::Result<()> {
16 let mut post = Post::find_or_fail(id).await?;
17 
18 if post.published_at.is_some() && !force {
19 console.info(format!("Post `{id}` is already published."));
20 
21 return Ok(());
22 }
23 
24 update!(post { published_at: laravel::now() }).await?;
25 
26 console.success(format!("Post `{id}` published."));
27 
28 Ok(())
29}

The function's doc comment becomes the description shown in list and --help, and each argument's doc comment documents that argument. Laravel discovers command functions automatically, so you can run the command immediately:

1laravel posts:publish 42 --force
2laravel posts:publish --help
1laravel posts:publish 42 --force
2laravel posts:publish --help

In addition to CLI arguments, a command may accept &mut Console for output and prompts, services via Inject<T>, config sections via Section<T>, and &Application, in any order. These injected parameters are excluded from command-line parsing. For example, the included inspire command takes Inject<Inspiring> to retrieve its quotes.

Arguments and options

A plain parameter like id above defines a positional argument. #[arg(..)] supports any of clap's argument attributes, including long for named options, short for single-letter flags, and default_value_t for default values. This version of posts:publish accepts multiple IDs and a --min-votes option:

1use laravel::console::{Console, command};
2 
3/// Publish draft posts.
4#[command("posts:publish")]
5pub async fn publish_posts(
6 /// The IDs of the posts to publish.
7 #[arg(required = true)]
8 ids: Vec<i64>,
9 /// Publish posts that are already published again.
10 #[arg(short, long)]
11 force: bool,
12 /// Publish only the posts with at least this many votes.
13 #[arg(long, value_name = "VOTES", default_value_t = 0)]
14 min_votes: i64,
15 console: &mut Console,
16) -> laravel::Result<()> {
17 // ...
18 
19 Ok(())
20}
1use laravel::console::{Console, command};
2 
3/// Publish draft posts.
4#[command("posts:publish")]
5pub async fn publish_posts(
6 /// The IDs of the posts to publish.
7 #[arg(required = true)]
8 ids: Vec<i64>,
9 /// Publish posts that are already published again.
10 #[arg(short, long)]
11 force: bool,
12 /// Publish only the posts with at least this many votes.
13 #[arg(long, value_name = "VOTES", default_value_t = 0)]
14 min_votes: i64,
15 console: &mut Console,
16) -> laravel::Result<()> {
17 // ...
18 
19 Ok(())
20}

Clap converts snake-case parameter names into kebab-case flags:

1laravel posts:publish 3 7 12 -f --min-votes=10
1laravel posts:publish 3 7 12 -f --min-votes=10

Each parameter's Rust type determines how clap parses it:

Type Command-line behavior
i64, String, PathBuf, and other parsed types Required value.
Option<T> Optional value.
bool with #[arg(long)] Boolean switch, such as --force.
Vec<T> Repeated value, such as --tag rust --tag laravel.
Enum deriving clap::ValueEnum with #[arg(value_enum)] One of the enum's variants, listed in --help.
Struct deriving clap::Args with #[command(flatten)] Shared group of options reused across commands.

Command-level attributes, such as aliases, follow the command name. Any of clap's command attributes are supported:

1#[command("posts:publish", visible_alias = "publish")]
1#[command("posts:publish", visible_alias = "publish")]

To derive clap traits, import clap from laravel::console rather than adding a separate clap dependency to your Cargo.toml.

Exit status

A command returning () or Ok(()) exits with status 0. To return a specific exit code, return u8 or laravel::Result<u8>. For example, this command exits with status 1 if the post is already published:

1use laravel::console::{Console, command};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[command("posts:publish")]
8pub async fn publish_post(id: i64, console: &mut Console) -> laravel::Result<u8> {
9 let mut post = Post::find_or_fail(id).await?;
10 
11 if post.published_at.is_some() {
12 console.error(format!("Post `{id}` is already published."));
13 
14 return Ok(1);
15 }
16 
17 update!(post { published_at: laravel::now() }).await?;
18 
19 Ok(0)
20}
1use laravel::console::{Console, command};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[command("posts:publish")]
8pub async fn publish_post(id: i64, console: &mut Console) -> laravel::Result<u8> {
9 let mut post = Post::find_or_fail(id).await?;
10 
11 if post.published_at.is_some() {
12 console.error(format!("Post `{id}` is already published."));
13 
14 return Ok(1);
15 }
16 
17 update!(post { published_at: laravel::now() }).await?;
18 
19 Ok(0)
20}

If a command returns Err or panics, Laravel prints the error to stderr, reports it through your error handler, and exits with status 1. In the example above, find_or_fail returns an error when the post does not exist, so propagating it with ? handles missing records cleanly.

Command structs

If you prefer organizing a command's input in a struct, derive clap::Parser on the struct and place #[laravel::console::command] on the impl block containing its handle method. The struct's fields define the CLI arguments, and handle accepts the same injected parameters as a command function:

1use laravel::console::{Console, clap};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[derive(clap::Parser)]
8#[command(name = "posts:publish")]
9pub struct PublishPost {
10 /// The ID of the post to publish.
11 id: i64,
12}
13 
14#[laravel::console::command]
15impl PublishPost {
16 async fn handle(self, console: &mut Console) -> laravel::Result<()> {
17 let mut post = Post::find_or_fail(self.id).await?;
18 
19 update!(post { published_at: laravel::now() }).await?;
20 
21 console.success(format!("Post `{}` published.", self.id));
22 
23 Ok(())
24 }
25}
1use laravel::console::{Console, clap};
2use laravel::model::update;
3 
4use crate::models::Post;
5 
6/// Publish a draft post.
7#[derive(clap::Parser)]
8#[command(name = "posts:publish")]
9pub struct PublishPost {
10 /// The ID of the post to publish.
11 id: i64,
12}
13 
14#[laravel::console::command]
15impl PublishPost {
16 async fn handle(self, console: &mut Console) -> laravel::Result<()> {
17 let mut post = Post::find_or_fail(self.id).await?;
18 
19 update!(post { published_at: laravel::now() }).await?;
20 
21 console.success(format!("Post `{}` published.", self.id));
22 
23 Ok(())
24 }
25}

Unlike command functions, command structs must be registered explicitly.

Registering commands

Laravel automatically discovers and registers every #[command] function in your application's app crate, regardless of which module it lives in, as long as the module is declared with mod.

Register command structs in src/app.rs using commands.add:

1Application::configure()
2 .with_commands(|commands, _config| {
3 commands.add::<PublishPost>();
4 })
1Application::configure()
2 .with_commands(|commands, _config| {
3 commands.add::<PublishPost>();
4 })

Registering a command with the same name replaces the previous definition, allowing your application to override package or framework commands. Packages register their commands through their service provider.

To run console commands on a recurring schedule, configure them in the task scheduler.

Writing output

Commands write status messages and primary output to separate streams so piped output stays clean. Status messages go to stderr with colored markers:

1console.info("Importing users...");
2console.warn("Skipping a duplicate.");
3console.error("Could not read users.csv.");
4console.step("Installing dependencies...");
5console.success("Imported.");
1console.info("Importing users...");
2console.warn("Skipping a duplicate.");
3console.error("Could not read users.csv.");
4console.step("Installing dependencies...");
5console.success("Imported.");

Primary output goes to stdout. Use line to print a plain line and new_line to print a blank line:

1console.line("Import complete.");
2console.new_line();
3console.line("Next steps...");
1console.line("Import complete.");
2console.new_line();
3console.line("Next steps...");

table also writes to stdout and wraps cells to fit the terminal width. Pass a header array and rows of matching length:

1let users = User::all().await?;
2 
3console.table(
4 ["Name", "Email"],
5 users.iter().map(|user| [&user.name, &user.email]),
6);
1let users = User::all().await?;
2 
3console.table(
4 ["Name", "Email"],
5 users.iter().map(|user| [&user.name, &user.email]),
6);

To display a titled message block on stderr, such as post-install instructions, use note:

1console.note("Next steps", "Review your configuration, then run the import.");
1console.note("Next steps", "Review your configuration, then run the import.");

Styled text

To style parts of a line, use markup. Tags accept fg, bg, and options separated by semicolons, and </> closes the tag:

1use laravel::console::escape_markup;
2 
3console.markup(
4 "<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>",
5);
6 
7let name = console.ask("What is your name?").await?;
8 
9console.markup(format!(
10 "<fg=sky-400>Hello, {}.</>",
11 escape_markup(&name),
12));
1use laravel::console::escape_markup;
2 
3console.markup(
4 "<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>",
5);
6 
7let name = console.ask("What is your name?").await?;
8 
9console.markup(format!(
10 "<fg=sky-400>Hello, {}.</>",
11 escape_markup(&name),
12));

Colors accept ANSI names such as red, Tailwind CSS colors such as emerald-400, or hex codes such as #ff8800. Always wrap untrusted or user-supplied text with escape_markup so < characters are not parsed as tags.

Quiet and verbose output

Every command supports the global --quiet (-q) and --verbose (-v) flags. Repeat -v up to three times to increase detail:

1laravel users:import -v
2laravel users:import -vvv
3laravel users:import --quiet
1laravel users:import -v
2laravel users:import -vvv
3laravel users:import --quiet

Write verbosity-gated messages using verbose, very_verbose, and debug. Each line prints only when the user passes that verbosity level or higher:

1console.info("Importing users...");
2console.verbose("Reading users.csv");
3console.very_verbose("Checking each user record");
4console.debug("Using the CSV importer");
1console.info("Importing users...");
2console.verbose("Reading users.csv");
3console.very_verbose("Checking each user record");
4console.debug("Using the CSV importer");
Flag Output shown
-q, --quiet console.error and command failures only.
None Standard messages, output, and progress displays.
-v Adds verbose lines.
-vv Adds very_verbose lines.
-vvv Adds debug lines.

When computing diagnostic output is expensive, check the verbosity level before doing the work:

1if console.is_verbose() {
2 let count = User::query().count().await?;
3 
4 console.verbose(format!("{count} users before the import"));
5}
1if console.is_verbose() {
2 let count = User::query().count().await?;
3 
4 console.verbose(format!("{count} users before the import"));
5}

Use is_very_verbose, is_debug, and is_quiet to check the other levels.

Prompting for input

When a command needs interactive input from the person running it, such as the name and email of a new user, use ask for text, password for hidden input, and confirm for yes-or-no questions:

1use laravel::console::{Console, command};
2use laravel::model::create;
3 
4use crate::models::User;
5 
6/// Create a user.
7#[command("user:create")]
8pub async fn create_user(console: &mut Console) -> laravel::Result<()> {
9 let name = console.ask("What is the user's name?").required(true).await?;
10 let email = console.ask("What is their email address?").required(true).await?;
11 let password = console.password("Choose a password").required(true).await?;
12 
13 if !console.confirm("Create the user?").default(true).await? {
14 return Ok(());
15 }
16 
17 create!(User {
18 name: &name,
19 email: &email,
20 password: &password,
21 })
22 .await?;
23 
24 console.success("User created.");
25 
26 Ok(())
27}
1use laravel::console::{Console, command};
2use laravel::model::create;
3 
4use crate::models::User;
5 
6/// Create a user.
7#[command("user:create")]
8pub async fn create_user(console: &mut Console) -> laravel::Result<()> {
9 let name = console.ask("What is the user's name?").required(true).await?;
10 let email = console.ask("What is their email address?").required(true).await?;
11 let password = console.password("Choose a password").required(true).await?;
12 
13 if !console.confirm("Create the user?").default(true).await? {
14 return Ok(());
15 }
16 
17 create!(User {
18 name: &name,
19 email: &email,
20 password: &password,
21 })
22 .await?;
23 
24 console.success("User created.");
25 
26 Ok(())
27}

ask and password return a String, while confirm returns a bool. You may provide a default that the user can accept by pressing Enter:

1let queue = console.ask("Which queue?").default("default").await?;
1let queue = console.ask("Which queue?").default("default").await?;

If the user presses Ctrl+C during a prompt, Laravel returns PromptError::Cancelled. Propagating it with ? exits the command with status 130 without reporting an error.

Validating answers

Passing .required(true) rejects empty answers. For custom validation rules, attach a validate closure that returns an error message when the input is invalid:

1let email = console
2 .ask("What is their email address?")
3 .placeholder("[email protected]")
4 .required(true)
5 .validate(|email: &String| {
6 if email.contains('@') {
7 Ok(())
8 } else {
9 Err("Enter an email address.")
10 }
11 })
12 .await?;
13 
14let password = console
15 .password("Choose a password")
16 .required(true)
17 .validate(|password: &String| {
18 if password.len() >= 8 {
19 Ok(())
20 } else {
21 Err("Use at least eight characters.")
22 }
23 })
24 .await?;
1let email = console
2 .ask("What is their email address?")
3 .placeholder("[email protected]")
4 .required(true)
5 .validate(|email: &String| {
6 if email.contains('@') {
7 Ok(())
8 } else {
9 Err("Enter an email address.")
10 }
11 })
12 .await?;
13 
14let password = console
15 .password("Choose a password")
16 .required(true)
17 .validate(|password: &String| {
18 if password.len() >= 8 {
19 Ok(())
20 } else {
21 Err("Use at least eight characters.")
22 }
23 })
24 .await?;

In an interactive terminal, validation errors re-prompt the user until they provide a valid answer. Because validate is synchronous, load any data it needs (such as existing emails) before displaying the prompt. placeholder renders dimmed hint text in an empty input without setting a default value.

Use choice to present a single-select menu navigated with arrow keys, and multiselect to allow toggling multiple options with the space bar. When given string options, choice returns a String and multiselect returns a Vec<String>:

1let queue = console
2 .choice("Which queue?", ["default", "high"])
3 .default("default")
4 .await?;
5 
6let roles = console
7 .multiselect("Which roles?", ["admin", "editor", "viewer"])
8 .default(["editor"])
9 .await?;
1let queue = console
2 .choice("Which queue?", ["default", "high"])
3 .default("default")
4 .await?;
5 
6let roles = console
7 .multiselect("Which roles?", ["admin", "editor", "viewer"])
8 .default(["editor"])
9 .await?;

Defaults match an option's value rather than its index. Chain .searchable() on either menu to let users filter options by typing, and .required(true) on multiselect to require at least one selection.

When you want an option's display label to differ from its returned value, pass Choice items. Each Choice can also include a hint and preserves your value's Rust type, such as an enum:

1use laravel::console::Choice;
2 
3#[derive(Clone, Debug, PartialEq, Eq)]
4enum Environment {
5 Production,
6 Staging,
7}
8 
9let environment = console
10 .choice(
11 "Which environment?",
12 [
13 Choice::new(Environment::Production, "Production")
14 .hint("Live customer traffic"),
15 Choice::new(Environment::Staging, "Staging")
16 .hint("Testing environment"),
17 ],
18 )
19 .default(Environment::Staging)
20 .await?;
1use laravel::console::Choice;
2 
3#[derive(Clone, Debug, PartialEq, Eq)]
4enum Environment {
5 Production,
6 Staging,
7}
8 
9let environment = console
10 .choice(
11 "Which environment?",
12 [
13 Choice::new(Environment::Production, "Production")
14 .hint("Live customer traffic"),
15 Choice::new(Environment::Staging, "Staging")
16 .hint("Testing environment"),
17 ],
18 )
19 .default(Environment::Staging)
20 .await?;

Defaults, validation callbacks, and scripted test answers all operate on the underlying choice values rather than their display labels.

Autocomplete and multiline answers

ask can suggest completions as the user types, using either a static list or a closure that receives the current input:

1let language = console
2 .ask("Which language?")
3 .autocomplete(["Rust", "Go", "TypeScript"])
4 .await?;
5 
6let emails = User::query().pluck(User::email).await?;
7 
8let email = console
9 .ask("Which user?")
10 .autocomplete(move |input: &str| {
11 emails
12 .iter()
13 .filter(|email| email.starts_with(input))
14 .cloned()
15 .collect()
16 })
17 .await?;
1let language = console
2 .ask("Which language?")
3 .autocomplete(["Rust", "Go", "TypeScript"])
4 .await?;
5 
6let emails = User::query().pluck(User::email).await?;
7 
8let email = console
9 .ask("Which user?")
10 .autocomplete(move |input: &str| {
11 emails
12 .iter()
13 .filter(|email| email.starts_with(input))
14 .cloned()
15 .collect()
16 })
17 .await?;

Autocomplete suggestions do not restrict what the user may enter, so add .validate(..) if the input must match a known option. Keep autocomplete closures fast since they run on every keystroke.

For longer responses, chain .multiline(). Pressing Enter inserts a newline; pressing Escape previews the text and Enter submits it:

1let description = console.ask("Describe your project").multiline().await?;
1let description = console.ask("Describe your project").multiline().await?;

Running unattended

When a deploy script or cron job runs your command, nobody is present to answer interactive prompts. Pass --no-interaction (-n) to automatically answer every prompt with its default value. Laravel also enters non-interactive mode automatically when stdin is not attached to a terminal. Every prompt (including confirmations) must define a .default(..) in non-interactive mode, or the command fails with PromptError::NonInteractive.

Because --quiet does not disable prompts on its own, pass both flags for fully unattended runs:

1laravel user:create --quiet --no-interaction
1laravel user:create --quiet --no-interaction

Showing progress

When a command processes thousands of records, displaying a progress bar shows how far along the work is. Use a progress bar when you know the total number of items, or a spinner when the total is unknown. For example, this command deletes unpublished drafts while advancing a progress bar:

1use laravel::console::{Console, command};
2 
3use crate::models::Post;
4 
5/// Delete every unpublished draft.
6#[command("posts:prune")]
7pub async fn prune_drafts(console: &mut Console) -> laravel::Result<()> {
8 let drafts = Post::query()
9 .filter(Post::published_at.is_null())
10 .get()
11 .await?;
12 
13 let mut progress = console.progress(drafts.len() as u64, "Deleting drafts...")?;
14 
15 for draft in drafts {
16 draft.delete().await?;
17 progress.advance(1);
18 }
19 
20 progress.finish("Drafts deleted.")?;
21 
22 Ok(())
23}
1use laravel::console::{Console, command};
2 
3use crate::models::Post;
4 
5/// Delete every unpublished draft.
6#[command("posts:prune")]
7pub async fn prune_drafts(console: &mut Console) -> laravel::Result<()> {
8 let drafts = Post::query()
9 .filter(Post::published_at.is_null())
10 .get()
11 .await?;
12 
13 let mut progress = console.progress(drafts.len() as u64, "Deleting drafts...")?;
14 
15 for draft in drafts {
16 draft.delete().await?;
17 progress.advance(1);
18 }
19 
20 progress.finish("Drafts deleted.")?;
21 
22 Ok(())
23}

A spinner follows the same lifecycle without a total count:

1let spinner = console.spinner("Loading users...")?;
2 
3let users = User::all().await?;
4 
5spinner.finish("Users loaded.")?;
1let spinner = console.spinner("Loading users...")?;
2 
3let users = User::all().await?;
4 
5spinner.finish("Users loaded.")?;

Call message to update the display's label and hint to render dimmed text underneath it. End any progress bar or spinner with finish, cancel, or fail. These methods only update the visual display; return an exit code or error from your command to control its exit status.

Because a progress display holds a mutable borrow of Console until finished, complete any interactive prompts before starting one.

Processing collections

progress_each iterates over a collection, runs an async closure for each item, and advances the progress bar automatically, returning the collected outputs in order. Here is posts:prune written with progress_each:

1let drafts = Post::query()
2 .filter(Post::published_at.is_null())
3 .get()
4 .await?;
5 
6console
7 .progress_each("Deleting drafts", drafts, async |draft, mut progress| {
8 progress.message(format!("Deleting {}", draft.title));
9 
10 draft.delete().await
11 })
12 .await?;
1let drafts = Post::query()
2 .filter(Post::published_at.is_null())
3 .get()
4 .await?;
5 
6console
7 .progress_each("Deleting drafts", drafts, async |draft, mut progress| {
8 progress.message(format!("Deleting {}", draft.title));
9 
10 draft.delete().await
11 })
12 .await?;

The collection must have a known length (such as a Vec, array, or range). If any iteration returns an error, progress_each stops immediately and returns that error.

Running work with a spinner

Use spin to show a spinner while an async closure executes and return its output:

1let users = console
2 .spin("Loading users...", async || User::all().await)
3 .await?;
1let users = console
2 .spin("Loading users...", async || User::all().await)
3 .await?;

If the closure returns an error, the spinner marks itself as failed and spin propagates the error.

To render multiple progress bars and spinners together under a shared heading, use progress_group.

Handling signals

The operating system sends your command a signal when someone presses Ctrl+C or when a process manager sends SIGTERM. By default, the command terminates immediately. To finish the current unit of work before exiting, call console.trap_shutdown and check is_requested at a safe checkpoint. For example, this command deletes drafts in pages and stops after finishing the current page:

1use laravel::console::{Console, command};
2use laravel::stream::TryStreamExt;
3 
4use crate::models::Post;
5 
6/// Delete every unpublished draft.
7#[command("posts:prune")]
8pub async fn prune_drafts(console: &mut Console) -> laravel::Result<u8> {
9 let shutdown = console.trap_shutdown()?;
10 
11 let mut pages = Post::query()
12 .filter(Post::published_at.is_null())
13 .chunk_by_id(100);
14 
15 while let Some(drafts) = pages.try_next().await? {
16 for draft in drafts {
17 draft.delete().await?;
18 }
19 
20 if shutdown.is_requested() {
21 console.info("Stopped. Run the command again to delete the rest.");
22 
23 return Ok(130);
24 }
25 }
26 
27 Ok(0)
28}
1use laravel::console::{Console, command};
2use laravel::stream::TryStreamExt;
3 
4use crate::models::Post;
5 
6/// Delete every unpublished draft.
7#[command("posts:prune")]
8pub async fn prune_drafts(console: &mut Console) -> laravel::Result<u8> {
9 let shutdown = console.trap_shutdown()?;
10 
11 let mut pages = Post::query()
12 .filter(Post::published_at.is_null())
13 .chunk_by_id(100);
14 
15 while let Some(drafts) = pages.try_next().await? {
16 for draft in drafts {
17 draft.delete().await?;
18 }
19 
20 if shutdown.is_requested() {
21 console.info("Stopped. Run the command again to delete the rest.");
22 
23 return Ok(130);
24 }
25 }
26 
27 Ok(0)
28}

trap_shutdown traps Ctrl+C (Signal::Interrupt) on all platforms and SIGTERM (Signal::Terminate) on Unix. Trapping a signal does not exit the command or change its exit status. Returning Ok(130) when interrupted follows the standard shell convention for Ctrl+C so calling scripts know the work did not finish.

The Shutdown handle returned by trap_shutdown is Clone and provides wait, so you can race an async operation against shutdown using task::select!:

1use laravel::task;
2 
3task::select! {
4 result = sync_feeds() => result?,
5 _ = shutdown.wait() => {
6 console.info("Shutting down...");
7 }
8}
1use laravel::task;
2 
3task::select! {
4 result = sync_feeds() => result?,
5 _ = shutdown.wait() => {
6 console.info("Shutting down...");
7 }
8}

To handle other signals, such as Signal::Hangup to reload configuration on Unix, register a callback with console.trap. Signal callbacks execute on the command's task while it awaits, so keep them brief and handle cleanup in your main loop:

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3 
4use laravel::console::Signal;
5 
6let reload = Arc::new(AtomicBool::new(false));
7let flag = Arc::clone(&reload);
8 
9console.trap(Signal::Hangup, move |_| {
10 flag.store(true, Ordering::Relaxed);
11})?;
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3 
4use laravel::console::Signal;
5 
6let reload = Arc::new(AtomicBool::new(false));
7let flag = Arc::clone(&reload);
8 
9console.trap(Signal::Hangup, move |_| {
10 flag.store(true, Ordering::Relaxed);
11})?;

Signal::Interrupt handles Ctrl+C on all platforms. On Unix, you may also trap Terminate, Hangup, Quit, User1, and User2.

Long-running commands

Commands such as serve, queue:work, or a custom feed poller run indefinitely until stopped. By default, Laravel wraps each command in a command span for its entire lifetime. On a command that never exits, that span stays open forever and groups all work into a single unfinished trace. Add long_running to the attribute so the command runs without an enclosing span:

1use laravel::console::command;
2use laravel::prelude::*;
3use laravel::task;
4 
5use crate::feeds;
6 
7/// Fetch new posts from every feed until stopped.
8#[command("feeds:watch", long_running)]
9pub async fn watch_feeds() -> laravel::Result<()> {
10 loop {
11 feeds::refresh().await?;
12 
13 task::sleep(5.minutes()).await;
14 }
15}
1use laravel::console::command;
2use laravel::prelude::*;
3use laravel::task;
4 
5use crate::feeds;
6 
7/// Fetch new posts from every feed until stopped.
8#[command("feeds:watch", long_running)]
9pub async fn watch_feeds() -> laravel::Result<()> {
10 loop {
11 feeds::refresh().await?;
12 
13 task::sleep(5.minutes()).await;
14 }
15}

For a command struct, write #[laravel::console::command(long_running)] on the impl block.

If a long-running command keeps state in memory that needs periodic upkeep, such as counters you flush to the database, you may enable your application's ticks for that command by adding with_ticks (for example, #[command("feeds:watch", long_running, with_ticks)]). Inside those ticks, the process host is Host::Command("feeds:watch"), and any tick marked with run_on_shutdown runs one final time when the command exits.

Background work

Console commands and scheduled callbacks can start background work with task::background or event::dispatch_background, like HTTP handlers do. When the command returns, Laravel waits for in-flight background work to finish before exiting. For example, this command announces a post to a webhook in the background:

1use laravel::console::{Console, command};
2use laravel::http::client;
3use laravel::task;
4use serde_json::json;
5 
6use crate::models::Post;
7 
8/// Announce a published post to the newsletter service.
9#[command("posts:announce")]
10pub async fn announce_post(id: i64, console: &mut Console) -> laravel::Result<()> {
11 let post = Post::find_or_fail(id).await?;
12 let title = post.title.clone();
13 
14 task::background(async move {
15 client::post("https://example.com/webhooks/announcements")
16 .json(json!({ "post_id": post.id, "title": post.title }))
17 .ensure_successful()
18 .await?;
19 
20 Ok(())
21 })?;
22 
23 console.success(format!("Announcing `{title}`."));
24 
25 Ok(())
26}
1use laravel::console::{Console, command};
2use laravel::http::client;
3use laravel::task;
4use serde_json::json;
5 
6use crate::models::Post;
7 
8/// Announce a published post to the newsletter service.
9#[command("posts:announce")]
10pub async fn announce_post(id: i64, console: &mut Console) -> laravel::Result<()> {
11 let post = Post::find_or_fail(id).await?;
12 let title = post.title.clone();
13 
14 task::background(async move {
15 client::post("https://example.com/webhooks/announcements")
16 .json(json!({ "post_id": post.id, "title": post.title }))
17 .ensure_successful()
18 .await?;
19 
20 Ok(())
21 })?;
22 
23 console.success(format!("Announcing `{title}`."));
24 
25 Ok(())
26}

Laravel waits up to SERVER_SHUTDOWN_TIMEOUT (20 seconds by default), and Ctrl+C or SIGTERM cuts the wait short. Background task failures are sent to your error handler without changing the command's exit status.

Testing commands

To test a command, pass the command string (the part after laravel) to app.command:

1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn it_publishes_a_post(app: Application) -> laravel::Result<()> {
8 let user = create!(User {
9 name: "Taylor",
10 email: "[email protected]",
11 password: "password",
12 })
13 .await?;
14 
15 let post = create!(Post {
16 title: "My first post",
17 user: &user,
18 })
19 .await?;
20 
21 app.command(&format!("posts:publish {}", post.id))
22 .await
23 .assert_successful()
24 .assert_error_output_contains("published.");
25 
26 Ok(())
27}
1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn it_publishes_a_post(app: Application) -> laravel::Result<()> {
8 let user = create!(User {
9 name: "Taylor",
10 email: "[email protected]",
11 password: "password",
12 })
13 .await?;
14 
15 let post = create!(Post {
16 title: "My first post",
17 user: &user,
18 })
19 .await?;
20 
21 app.command(&format!("posts:publish {}", post.id))
22 .await
23 .assert_successful()
24 .assert_error_output_contains("published.");
25 
26 Ok(())
27}

The command executes in the test's process, and the returned assertion helper captures stdout and stderr separately. line and table output go to stdout (assert_output_contains), while status messages, notes, and progress go to stderr (assert_error_output_contains). Use assert_output_missing, assert_error_output_missing, and assert_no_output to check absent output, and assert_exit_code or assert_failed to verify exit codes.

app.command splits the string using shell-like quoting without invoking a shell. To pass exact argument strings directly, use app.command_args(["posts:publish", "42", "--force"]).

To test interactive prompts, script the answers in the order the command asks them before awaiting:

1#[laravel::test]
2async fn it_creates_a_user(app: Application) {
3 app.command("user:create")
4 .expects_question("What is the user's name?", "Taylor")
5 .expects_question("What is their email address?", "[email protected]")
6 .expects_password("Choose a password", "secret-password")
7 .expects_confirmation("Create the user?", true)
8 .await
9 .assert_successful();
10}
1#[laravel::test]
2async fn it_creates_a_user(app: Application) {
3 app.command("user:create")
4 .expects_question("What is the user's name?", "Taylor")
5 .expects_question("What is their email address?", "[email protected]")
6 .expects_password("Choose a password", "secret-password")
7 .expects_confirmation("Create the user?", true)
8 .await
9 .assert_successful();
10}

Use expects_choice and expects_multiselect for menus, passing the underlying choice values such as Environment::Staging. Once you script any answer, you must script every prompt the command asks; the test fails on an unused expectation, an unexpected prompt, or an answer rejected by validation. Without scripted answers, each prompt uses its default.

To test signal traps, send a simulated signal with sends_signal:

1use laravel::console::Signal;
2 
3app.command("posts:prune")
4 .sends_signal(Signal::Interrupt)
5 .await
6 .assert_successful();
1use laravel::console::Signal;
2 
3app.command("posts:prune")
4 .sends_signal(Signal::Interrupt)
5 .await
6 .assert_successful();

Tests do not wait for a command's background work.

Commands execute their real side effects in tests. For example, running key:generate without --show modifies .env in your working directory. serve cannot run inside a test; test your routes with HTTP tests instead.