Console
- Introduction
- Writing commands
- Registering commands
- Writing output
- Prompting for input
- Showing progress
- Handling signals
- Background work
- Testing commands
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 application2laravel route:list # run a command3laravel list # list every command4laravel help route:list # show a command's help1laravel serve # serve the application2laravel route:list # run a command3laravel list # list every command4laravel 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;34use crate::models::Post;56/// 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?;1718 if post.published_at.is_some() && !force {19 console.info(format!("Post `{id}` is already published."));2021 return Ok(());22 }2324 update!(post { published_at: laravel::now() }).await?;2526 console.success(format!("Post `{id}` published."));2728 Ok(())29}1use laravel::console::{Console, command};2use laravel::model::update;34use crate::models::Post;56/// 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?;1718 if post.published_at.is_some() && !force {19 console.info(format!("Post `{id}` is already published."));2021 return Ok(());22 }2324 update!(post { published_at: laravel::now() }).await?;2526 console.success(format!("Post `{id}` published."));2728 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 --force2laravel posts:publish --help1laravel posts:publish 42 --force2laravel 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};23/// 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 // ...1819 Ok(())20}1use laravel::console::{Console, command};23/// 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 // ...1819 Ok(())20}
Clap converts snake-case parameter names into kebab-case flags:
1laravel posts:publish 3 7 12 -f --min-votes=101laravel 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;34use crate::models::Post;56/// 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?;1011 if post.published_at.is_some() {12 console.error(format!("Post `{id}` is already published."));1314 return Ok(1);15 }1617 update!(post { published_at: laravel::now() }).await?;1819 Ok(0)20}1use laravel::console::{Console, command};2use laravel::model::update;34use crate::models::Post;56/// 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?;1011 if post.published_at.is_some() {12 console.error(format!("Post `{id}` is already published."));1314 return Ok(1);15 }1617 update!(post { published_at: laravel::now() }).await?;1819 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;34use crate::models::Post;56/// 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}1314#[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?;1819 update!(post { published_at: laravel::now() }).await?;2021 console.success(format!("Post `{}` published.", self.id));2223 Ok(())24 }25}1use laravel::console::{Console, clap};2use laravel::model::update;34use crate::models::Post;56/// 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}1314#[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?;1819 update!(post { published_at: laravel::now() }).await?;2021 console.success(format!("Post `{}` published.", self.id));2223 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?;23console.table(4 ["Name", "Email"],5 users.iter().map(|user| [&user.name, &user.email]),6);1let users = User::all().await?;23console.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;23console.markup(4 "<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>",5);67let name = console.ask("What is your name?").await?;89console.markup(format!(10 "<fg=sky-400>Hello, {}.</>",11 escape_markup(&name),12));1use laravel::console::escape_markup;23console.markup(4 "<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>",5);67let name = console.ask("What is your name?").await?;89console.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 -v2laravel users:import -vvv3laravel users:import --quiet1laravel users:import -v2laravel users:import -vvv3laravel 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?;34 console.verbose(format!("{count} users before the import"));5}1if console.is_verbose() {2 let count = User::query().count().await?;34 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;34use crate::models::User;56/// 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?;1213 if !console.confirm("Create the user?").default(true).await? {14 return Ok(());15 }1617 create!(User {18 name: &name,19 email: &email,20 password: &password,21 })22 .await?;2324 console.success("User created.");2526 Ok(())27}1use laravel::console::{Console, command};2use laravel::model::create;34use crate::models::User;56/// 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?;1213 if !console.confirm("Create the user?").default(true).await? {14 return Ok(());15 }1617 create!(User {18 name: &name,19 email: &email,20 password: &password,21 })22 .await?;2324 console.success("User created.");2526 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 = console2 .ask("What is their email address?")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?;1314let password = console15 .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 = console2 .ask("What is their email address?")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?;1314let password = console15 .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.
Menus
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 = console2 .choice("Which queue?", ["default", "high"])3 .default("default")4 .await?;56let roles = console7 .multiselect("Which roles?", ["admin", "editor", "viewer"])8 .default(["editor"])9 .await?;1let queue = console2 .choice("Which queue?", ["default", "high"])3 .default("default")4 .await?;56let roles = console7 .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;23#[derive(Clone, Debug, PartialEq, Eq)]4enum Environment {5 Production,6 Staging,7}89let environment = console10 .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;23#[derive(Clone, Debug, PartialEq, Eq)]4enum Environment {5 Production,6 Staging,7}89let environment = console10 .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 = console2 .ask("Which language?")3 .autocomplete(["Rust", "Go", "TypeScript"])4 .await?;56let emails = User::query().pluck(User::email).await?;78let email = console9 .ask("Which user?")10 .autocomplete(move |input: &str| {11 emails12 .iter()13 .filter(|email| email.starts_with(input))14 .cloned()15 .collect()16 })17 .await?;1let language = console2 .ask("Which language?")3 .autocomplete(["Rust", "Go", "TypeScript"])4 .await?;56let emails = User::query().pluck(User::email).await?;78let email = console9 .ask("Which user?")10 .autocomplete(move |input: &str| {11 emails12 .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-interaction1laravel 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};23use crate::models::Post;45/// 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?;1213 let mut progress = console.progress(drafts.len() as u64, "Deleting drafts...")?;1415 for draft in drafts {16 draft.delete().await?;17 progress.advance(1);18 }1920 progress.finish("Drafts deleted.")?;2122 Ok(())23}1use laravel::console::{Console, command};23use crate::models::Post;45/// 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?;1213 let mut progress = console.progress(drafts.len() as u64, "Deleting drafts...")?;1415 for draft in drafts {16 draft.delete().await?;17 progress.advance(1);18 }1920 progress.finish("Drafts deleted.")?;2122 Ok(())23}
A spinner follows the same lifecycle without a total count:
1let spinner = console.spinner("Loading users...")?;23let users = User::all().await?;45spinner.finish("Users loaded.")?;1let spinner = console.spinner("Loading users...")?;23let users = User::all().await?;45spinner.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?;56console7 .progress_each("Deleting drafts", drafts, async |draft, mut progress| {8 progress.message(format!("Deleting {}", draft.title));910 draft.delete().await11 })12 .await?;1let drafts = Post::query()2 .filter(Post::published_at.is_null())3 .get()4 .await?;56console7 .progress_each("Deleting drafts", drafts, async |draft, mut progress| {8 progress.message(format!("Deleting {}", draft.title));910 draft.delete().await11 })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 = console2 .spin("Loading users...", async || User::all().await)3 .await?;1let users = console2 .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;34use crate::models::Post;56/// 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()?;1011 let mut pages = Post::query()12 .filter(Post::published_at.is_null())13 .chunk_by_id(100);1415 while let Some(drafts) = pages.try_next().await? {16 for draft in drafts {17 draft.delete().await?;18 }1920 if shutdown.is_requested() {21 console.info("Stopped. Run the command again to delete the rest.");2223 return Ok(130);24 }25 }2627 Ok(0)28}1use laravel::console::{Console, command};2use laravel::stream::TryStreamExt;34use crate::models::Post;56/// 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()?;1011 let mut pages = Post::query()12 .filter(Post::published_at.is_null())13 .chunk_by_id(100);1415 while let Some(drafts) = pages.try_next().await? {16 for draft in drafts {17 draft.delete().await?;18 }1920 if shutdown.is_requested() {21 console.info("Stopped. Run the command again to delete the rest.");2223 return Ok(130);24 }25 }2627 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;23task::select! {4 result = sync_feeds() => result?,5 _ = shutdown.wait() => {6 console.info("Shutting down...");7 }8}1use laravel::task;23task::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};34use laravel::console::Signal;56let reload = Arc::new(AtomicBool::new(false));7let flag = Arc::clone(&reload);89console.trap(Signal::Hangup, move |_| {10 flag.store(true, Ordering::Relaxed);11})?;1use std::sync::Arc;2use std::sync::atomic::{AtomicBool, Ordering};34use laravel::console::Signal;56let reload = Arc::new(AtomicBool::new(false));7let flag = Arc::clone(&reload);89console.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;45use crate::feeds;67/// 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?;1213 task::sleep(5.minutes()).await;14 }15}1use laravel::console::command;2use laravel::prelude::*;3use laravel::task;45use crate::feeds;67/// 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?;1213 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;56use crate::models::Post;78/// 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();1314 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?;1920 Ok(())21 })?;2223 console.success(format!("Announcing `{title}`."));2425 Ok(())26}1use laravel::console::{Console, command};2use laravel::http::client;3use laravel::task;4use serde_json::json;56use crate::models::Post;78/// 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();1314 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?;1920 Ok(())21 })?;2223 console.success(format!("Announcing `{title}`."));2425 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::*;34use app::models::{Post, User};56#[laravel::test]7async fn it_publishes_a_post(app: Application) -> laravel::Result<()> {8 let user = create!(User {9 name: "Taylor",11 password: "password",12 })13 .await?;1415 let post = create!(Post {16 title: "My first post",17 user: &user,18 })19 .await?;2021 app.command(&format!("posts:publish {}", post.id))22 .await23 .assert_successful()24 .assert_error_output_contains("published.");2526 Ok(())27}1use laravel::model::create;2use laravel::testing::prelude::*;34use app::models::{Post, User};56#[laravel::test]7async fn it_publishes_a_post(app: Application) -> laravel::Result<()> {8 let user = create!(User {9 name: "Taylor",11 password: "password",12 })13 .await?;1415 let post = create!(Post {16 title: "My first post",17 user: &user,18 })19 .await?;2021 app.command(&format!("posts:publish {}", post.id))22 .await23 .assert_successful()24 .assert_error_output_contains("published.");2526 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")6 .expects_password("Choose a password", "secret-password")7 .expects_confirmation("Create the user?", true)8 .await9 .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")6 .expects_password("Choose a password", "secret-password")7 .expects_confirmation("Create the user?", true)8 .await9 .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;23app.command("posts:prune")4 .sends_signal(Signal::Interrupt)5 .await6 .assert_successful();1use laravel::console::Signal;23app.command("posts:prune")4 .sends_signal(Signal::Interrupt)5 .await6 .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.