跳至正文

Console ​

Introduction ​

Not every task in your application begins with an HTTP request. You may need to import a CSV file every night, delete stale drafts, or fix a few rows in production. Console commands handle these tasks from your application's own binary, with full access to your configuration, services, and models.

Running your application's binary with no command serves your application. Passing a command name runs that command instead. While you develop, run commands through the Laravel CLI, which builds your application and then runs the command you name:

shell
laravel serve                 # serve the application
laravel route:list            # run a command
laravel list                  # list every command
laravel 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 receives a context that carries your application, so config.From(ctx), your database queries, and your log channels work as they do in handlers. Because there is no incoming HTTP request, a command has no session or cookies.

Writing commands ​

Beyond the built-in commands, you may write your own. New applications keep each command in its own file in the commands package. To start a new command, run make:command with the name you'll type to run it:

shell
laravel make:command posts:prune

make:command writes commands/prune_posts.go and adds the command to the All list in commands/commands.go, which your application registers. A command is a type with a Name, which you type to run it, a Description, which list and --help show, and a Run method, which does the work. For example, this command deletes drafts that nobody has edited in a while:

go
package commands

import (
	"context"
	"flag"

	"go.laravel.com/console"
	"go.laravel.com/date"
	"go.laravel.com/db"
)

// PrunePosts deletes stale drafts.
type PrunePosts struct {
	days int
}

func (*PrunePosts) Name() string        { return "posts:prune" }
func (*PrunePosts) Description() string { return "Delete drafts that nobody has edited in a while" }

func (p *PrunePosts) Flags(flags *flag.FlagSet) {
	flags.IntVar(&p.days, "days", 30, "Delete drafts last edited more than this many `days` ago")
}

func (p *PrunePosts) Run(ctx context.Context, c *console.Console) error {
	cutoff := date.Now(ctx).AddDate(0, 0, -p.days)

	deleted, err := db.Table("posts").
		WhereNull("published_at").
		Where("updated_at", "<", cutoff).
		Delete(ctx)
	if err != nil {
		return err
	}

	c.Successf("Deleted %d drafts.", deleted)

	return nil
}

Once the command is in the All list, you may run it and read its help:

shell
laravel posts:prune --days=90
laravel posts:prune --help

The ctx that Run receives carries your application, as r does in a handler, so the queries you run with ctx use your application's database. services.From(ctx) returns your application's own services, such as a payment provider's client. The *console.Console, c, writes the command's output and asks its questions.

Arguments and options ​

The Flags method declares the command's options on a standard flag.FlagSet, usually bound to the command's fields, as --days is bound to p.days above. Laravel parses the options before it calls Run and lists them in --help. Each run starts from the defaults you declared, so an option set on one run doesn't carry over to the next. If a command has no options, leave out Flags.

Sometimes a command needs values that aren't options, such as the IDs of the posts to publish. Laravel puts the arguments that follow the options in c.Args. Describe them in an Arguments method, so --help lists them and Laravel exits with status 2 when a required argument is missing. This command publishes the posts whose IDs it receives, and accepts a --force switch to publish posts that are already published again:

go
package commands

import (
	"context"
	"flag"

	laravel "go.laravel.com"
	"go.laravel.com/console"
	"go.laravel.com/date"
	"go.laravel.com/db"
)

// PublishPosts publishes draft posts.
type PublishPosts struct {
	force bool
}

func (*PublishPosts) Name() string        { return "posts:publish" }
func (*PublishPosts) Description() string { return "Publish draft posts" }

func (p *PublishPosts) Flags(flags *flag.FlagSet) {
	flags.BoolVar(&p.force, "force", false, "Publish posts that are already published again")
}

func (*PublishPosts) Arguments() []laravel.Argument {
	return []laravel.Argument{
		{Name: "ID", Description: "The IDs of the posts to publish", Required: true, Many: true},
	}
}

func (p *PublishPosts) Run(ctx context.Context, c *console.Console) error {
	posts := db.Table("posts").WhereIn("id", c.Args)
	if !p.force {
		posts = posts.WhereNull("published_at")
	}

	published, err := posts.Update(ctx, db.Values{"published_at": date.Now(ctx)})
	if err != nil {
		return err
	}

	c.Successf("Published %d posts.", published)

	return nil
}
shell
laravel posts:publish 3 7 12 --force

Without an Arguments method, a command takes no arguments, and Laravel rejects any it receives. Every command also accepts -q, -v, -vv, and -vvv for its output, -n for its prompts, and -h for its help, so your commands can't declare options with those names.

Exit status ​

A command whose Run returns nil exits with status 0. If Run returns an error or panics, Laravel prints the error, reports it through your report hook, and exits with status 1. So if a nightly import can't reach the server it reads from, the error reaches your error tracker as well as the cron log, and you don't need to report it yourself before you return it. A mistake on the command line, such as an option the command doesn't have, exits with status 2 and shows the command's usage.

Sometimes a script that runs your command needs a status of its own, such as a check that exits with 3 when it finds problems. Return console.Exit with the status, and Laravel exits with that status without printing or reporting anything more:

go
if len(problems) > 0 {
	c.Errorf("%d posts have broken links.", len(problems))

	return console.Exit(3)
}

Registering commands ​

Your application lists its commands in commands/commands.go, and make:command adds each new command to the end of the list. When you write a command by hand, add it to All yourself:

go
var All = []laravel.Command{
	&PrunePosts{},
	&PublishPosts{},
}

bootstrap/app.go registers the list through the Commands option:

go
func Options() laravel.Options {
	return laravel.Options{
		// ...
		Commands: commands.All,
	}
}

The list command shows your commands beside Laravel's, grouped by the prefix before the colon, such as posts. If you run a command often, you may give it a shorter name to type as well. Add an Aliases method that lists the other names, and the command's help shows them:

go
func (*PublishPosts) Aliases() []string { return []string{"publish"} }

Packages may add commands too. If one of your commands has the same name as a package's command, your command replaces the package's. If it has the same name or alias as one of Laravel's commands, or as another of your own, the application refuses to start, and the error names the duplicate command.

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

Writing output ​

While a command works, it tells the person running it what it's doing and what it did. Each message starts with a colored marker. Messages go to standard error, and the command's results, such as Line and Table output, go to standard output, so a script piping the command's output gets only its results:

go
c.Info("Importing users...")
c.Step("Reading users.csv...")
c.Success("Imported.")

c.Warn("Skipping a duplicate.")
c.Error("Could not read users.csv.")

Use Line to write a plain line of text and NewLine to write an empty line:

go
c.Line("Import complete.")
c.NewLine()
c.Line("Next steps...")

Table writes rows under their headers to standard output, wrapping cells to fit the terminal's width. To color a cell by its value, such as a status, pass it through Paint with a tone: console.Success, console.Warning, console.Error, console.Info, console.Accent, or console.Muted. The columns still line up:

go
c.Table([]string{"Invoice", "Status"}, [][]string{
	{"1024", c.Paint(console.Success, "Paid")},
	{"1025", c.Paint(console.Warning, "Overdue")},
})

Each method has a version ending in f that formats its message as fmt.Sprintf does:

go
c.Successf("Imported %d users.", imported)
c.Linef("%d rows skipped", skipped)

To display a titled message block, such as the next steps after an install, use Note:

go
c.Note("Next steps", "Review your configuration, then run the import.")

If you use a library that writes to an io.Writer, such as an encoding/csv writer, pass it c.Stdout().

Styled text ​

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

go
c.Markup("<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>")

name, err := c.Ask(ctx, "What is your name?")
if err != nil {
	return err
}

c.Markup("<fg=sky-400>Hello, " + console.Escape(name) + ".</>")

Colors accept ANSI names such as red, Tailwind CSS colors such as emerald-400, or hex codes such as #ff8800. Always wrap text you didn't write, such as the user's answer above, in console.Escape, so a < in the text isn't read as a tag. When the output isn't a terminal, Markup writes the text without its styles.

Quiet and verbose output ​

Every command accepts the --quiet (-q) and --verbose (-v) options. Repeat -v up to three times for more detail:

shell
laravel users:import -v
laravel users:import -vvv
laravel users:import --quiet

Write lines that only appear with more detail using Verbose, VeryVerbose, and Debug, or their versions ending in f. Each line prints only when the person passes that level or higher:

go
c.Info("Importing users...")
c.Verbose("Reading users.csv")
c.VeryVerbose("Checking each user record")
c.Debug("Using the CSV importer")
OptionOutput shown
-q, --quietc.Error and command failures only.
NoneStandard messages, results, and progress.
-vAdds Verbose lines.
-vvAdds VeryVerbose lines.
-vvvAdds Debug lines.

When working out a detail is expensive, such as a count that runs a query, compare c.Verbosity with the level first, so the query only runs when the line will show:

go
if c.Verbosity >= console.Verbose {
	count, err := db.Table("users").Count(ctx)
	if err != nil {
		return err
	}

	c.Verbosef("%d users before the import", count)
}

Prompting for input ​

When a command needs answers from the person running it, such as the name and email address of a new user, you may ask for them. Use Ask for text, Secret for input that stays hidden as it's typed, such as a password, and Confirm for yes or no questions:

go
package commands

import (
	"context"

	"go.laravel.com/console"
	"go.laravel.com/db"
	"go.laravel.com/hash"
)

// CreateUser creates a user.
type CreateUser struct{}

func (*CreateUser) Name() string        { return "user:create" }
func (*CreateUser) Description() string { return "Create a user" }

func (*CreateUser) Run(ctx context.Context, c *console.Console) error {
	name, err := c.Ask(ctx, "What is the user's name?", console.Required())
	if err != nil {
		return err
	}

	email, err := c.Ask(ctx, "What is their email address?", console.Required())
	if err != nil {
		return err
	}

	password, err := c.Secret(ctx, "Choose a password", console.Required())
	if err != nil {
		return err
	}

	create, err := c.Confirm(ctx, "Create the user?", true)
	if err != nil || !create {
		return err
	}

	hashed, err := hash.Make(ctx, password)
	if err != nil {
		return err
	}

	err = db.Table("users").Insert(ctx, db.Values{"name": name, "email": email, "password": hashed})
	if err != nil {
		return err
	}

	c.Success("User created.")

	return nil
}

Ask and Secret return a string, while Confirm returns a bool. The last argument to Confirm is the answer the person gets by pressing Enter. To give Ask a default that the person can accept by pressing Enter, pass console.Default:

go
queue, err := c.Ask(ctx, "Which queue?", console.Default("default"))

Each prompt takes the command's context, so if the person presses Ctrl+C during a prompt, the prompt returns the context's error. Returning that error exits the command with status 130 without reporting an error.

Validating answers ​

Passing console.Required() rejects empty answers. For rules of your own, pass console.Validate with a function that returns an error when the answer is invalid. The prompt shows the error's message and asks again until the person gives a valid answer:

go
email, err := c.Ask(ctx, "What is their email address?",
	console.Placeholder("you@example.com"),
	console.Required(),
	console.Validate(func(email string) error {
		if !strings.Contains(email, "@") {
			return errors.New("Enter an email address.")
		}

		return nil
	}),
)

console.Placeholder shows dimmed example text in an empty answer without making the example the answer. console.Hint shows a line under the question, such as what the answer is for:

go
email, err := c.Ask(ctx, "What is their email address?",
	console.Hint("We'll send the welcome email here."),
)

When the answer must be one of a few values, such as an environment, show a menu. Choice asks for one choice, which the person picks with the arrow keys, and returns it. MultiChoice lets the person pick several with the space bar, and returns them in the order you listed them:

go
env, err := c.Choice(ctx, "Which environment?", []string{"production", "staging"},
	console.Default("staging"),
)
if err != nil {
	return err
}

roles, err := c.MultiChoice(ctx, "Which roles?", []string{"admin", "editor", "viewer"},
	console.Defaults("editor"),
)

A default must be one of the choices, and console.Defaults lists the choices that MultiChoice starts with picked. Add console.Searchable() to either menu to let the person filter the choices by typing, and console.Required() to make MultiChoice require at least one choice.

When you want a choice's label to differ from the value it returns, such as an environment constant of your own or a record's ID beside its name, pass console.Item values to c.Select. Each item has the Value that Select returns, the Label the menu shows, and an optional Hint shown dimmed beside the label:

go
type Environment int

const (
	Production Environment = iota + 1
	Staging
)

env, err := c.Select(ctx, "Which environment?", []console.Item[Environment]{
	{Value: Production, Label: "Production", Hint: "Live customer traffic"},
	{Value: Staging, Label: "Staging", Hint: "Testing environment"},
}, console.Default(Staging))

c.MultiSelect does the same for several choices and returns their values. Defaults and validation functions take the items' values, such as Staging, rather than their labels.

Suggestions and multiline answers ​

Ask can suggest answers as the person types, from either a fixed list with console.Suggest or a function of what's typed so far with console.SuggestFunc. Tab takes the highlighted suggestion:

go
language, err := c.Ask(ctx, "Which language?", console.Suggest("Go", "Python", "TypeScript"))
if err != nil {
	return err
}

emails, err := db.Table("users").Pluck[string](ctx, "email")
if err != nil {
	return err
}

email, err := c.Ask(ctx, "Which user?", console.SuggestFunc(func(input string) []string {
	var matches []string
	for _, email := range emails {
		if strings.HasPrefix(email, input) {
			matches = append(matches, email)
		}
	}

	return matches
}))

Suggestions don't restrict what the person may enter, so add console.Validate if the answer must match a known option. The function runs on every key the person presses, so load what it needs first, as this command loads emails, rather than querying the database inside the function.

For longer answers, add console.Multiline(). Pressing Enter starts a new line, and pressing Escape shows the whole answer, which Enter then submits:

go
description, err := c.Ask(ctx, "Describe your project", console.Multiline())

Running unattended ​

When a deploy script or cron job runs your command, nobody is there to answer its prompts. Pass --no-interaction (-n), and each prompt takes its default. Laravel does the same when standard input isn't a terminal. A prompt without a default then fails, and the error names the question, so give each prompt of a command that may run unattended a default, or an option that skips the prompt, as migrate --force skips its confirmation.

Because --quiet doesn't turn off prompts on its own, pass both options for fully unattended runs:

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

Showing progress ​

When a command works through thousands of records, a progress bar shows the person running it how far along the work is. Use a progress bar when you know the total number of items, or a spinner when you don't. For example, this command deletes unpublished drafts while advancing a progress bar:

go
package commands

import (
	"context"

	"go.laravel.com/console"
	"go.laravel.com/model"

	"app/models"
)

// PrunePosts deletes unpublished drafts.
type PrunePosts struct{}

func (*PrunePosts) Name() string        { return "posts:prune" }
func (*PrunePosts) Description() string { return "Delete every unpublished draft" }

func (*PrunePosts) Run(ctx context.Context, c *console.Console) error {
	drafts, err := model.Query[models.Post]().WhereNull("published_at").Get(ctx)
	if err != nil {
		return err
	}

	bar := c.Progress(len(drafts), "Deleting drafts...")

	for _, draft := range drafts {
		if err := model.Delete(ctx, &draft); err != nil {
			bar.Fail("Couldn't delete the drafts.")

			return err
		}

		bar.Advance(1)
	}

	bar.Finish("Drafts deleted.")

	return nil
}

A spinner follows the same lifecycle without a total count:

go
spinner := c.Spinner("Loading users...")

users, err := model.Query[models.User]().Get(ctx)
if err != nil {
	spinner.Fail("Couldn't load the users.")

	return err
}

spinner.Finish("Users loaded.")

Call Message to change the display's label and Hint to show dimmed text under it. End every progress bar or spinner with Finish, Cancel, or Fail. These methods only change what the terminal shows, so return an error from Run to fail the command as well. You may call Advance from several goroutines at once.

While a progress bar or spinner is showing, the messages your command writes, such as c.Warn, appear above it. Ask any questions before you start one, and show one at a time. When the output isn't a terminal, such as in a log file, a progress bar shows only the message it ends with.

Processing collections ​

c.ProgressEach runs a function for each item of a slice and advances the progress bar after each one. Here is posts:prune written with ProgressEach:

go
drafts, err := model.Query[models.Post]().WhereNull("published_at").Get(ctx)
if err != nil {
	return err
}

return c.ProgressEach(
	"Deleting drafts...",
	drafts,
	func(draft models.Post, bar *console.Progress) error {
		bar.Message("Deleting " + draft.Title + "...")

		return model.Delete(ctx, &draft)
	},
)

If the function returns an error, ProgressEach stops at once, fails the progress bar, and returns the error.

Running work with a spinner ​

Use c.Spin to show a spinner while a function runs and return what the function returns:

go
users, err := c.Spin("Loading users...", func() ([]models.User, error) {
	return model.Query[models.User]().Get(ctx)
})

If the function returns an error, the spinner shows the failure and Spin returns the error.

To show several progress bars and spinners together under one heading, such as for work that runs in goroutines of its own, start them from the *console.ProgressGroup that c.ProgressGroup returns, then end that group with Finish.

Handling signals ​

The operating system sends your command a signal when someone presses Ctrl+C or when a process manager sends SIGTERM. By default, Laravel then ends the context that Run receives, so a query in progress fails. If your command returns an error that wraps the context's error, it exits with status 130 and prints nothing more, and a second Ctrl+C ends the process at once.

Sometimes a command shouldn't stop partway through a step. To finish the current unit of work before exiting, trap the signal. List the signals in a Signals method, and Laravel sends them to c.Signals instead of ending the command's context, so you may stop at a safe checkpoint. console.ShutdownSignals() returns the standard shutdown signals for the current platform (os.Interrupt and SIGTERM on Unix, os.Interrupt on Windows). For example, this command deletes drafts a hundred at a time and stops after finishing the current page:

go
package commands

import (
	"context"
	"os"

	"go.laravel.com/console"
	"go.laravel.com/db"
)

// PrunePosts deletes unpublished drafts.
type PrunePosts struct{}

func (*PrunePosts) Name() string         { return "posts:prune" }
func (*PrunePosts) Description() string  { return "Delete every unpublished draft" }
func (*PrunePosts) Signals() []os.Signal { return console.ShutdownSignals() }

func (*PrunePosts) Run(ctx context.Context, c *console.Console) error {
	for {
		ids, err := db.Table("posts").
			WhereNull("published_at").
			OrderBy("id").
			Limit(100).
			Pluck[int64](ctx, "id")
		if err != nil || len(ids) == 0 {
			return err
		}

		if _, err := db.Table("posts").WhereIn("id", ids).Delete(ctx); err != nil {
			return err
		}

		select {
		case <-c.Signals:
			c.Info("Stopped. Run the command again to delete the rest.")

			return console.Exit(130)
		default:
		}
	}
}

Trapping a signal doesn't stop the command or change its exit status, and a second Ctrl+C doesn't end the process either. Returning console.Exit(130) when interrupted follows the standard shell convention for Ctrl+C, so calling scripts know the work didn't finish. A prompt still stops when the signal arrives while it waits for an answer, and the command exits with status 130.

os.Interrupt handles Ctrl+C on every platform. On Unix, you may also trap syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGUSR1, and syscall.SIGUSR2.

Long-running commands ​

Commands such as serve, queue:work, or a feed poller of your own run until they're stopped. Wait for the context with select, and return when the context ends. By default, Laravel runs each command inside a trace span for its whole lifetime. On a command that never exits, that span stays open forever and groups all of the command's work into a single unfinished trace. Add a LongRunning method that returns true, and the command runs without the span:

go
package commands

import (
	"context"
	"time"

	"go.laravel.com/console"

	"app/feeds"
)

// WatchFeeds fetches new posts until it's stopped.
type WatchFeeds struct{}

func (*WatchFeeds) Name() string        { return "feeds:watch" }
func (*WatchFeeds) Description() string { return "Fetch new posts from every feed until stopped" }
func (*WatchFeeds) LongRunning() bool   { return true }

func (*WatchFeeds) Run(ctx context.Context, c *console.Console) error {
	ticker := time.NewTicker(5 * time.Minute)
	defer ticker.Stop()

	for {
		if err := feeds.Refresh(ctx); err != nil {
			return err
		}

		select {
		case <-ctx.Done():
			return nil
		case <-ticker.C:
		}
	}
}

When the work only needs to happen on a timetable, schedule it instead, so you don't need a process manager to keep the command running.

If a long-running command keeps state in memory that needs periodic upkeep, such as counters you flush to the database, enable your application's ticks for that command by adding a WithTicks method returning true:

go
func (*WatchFeeds) LongRunning() bool { return true }
func (*WatchFeeds) WithTicks() bool   { return true }

Inside those ticks, laravel.CurrentHost(ctx) reports HostCommand with Command set to "feeds:watch", and any tick with RunOnShutdown runs one final time when the command exits.

Background work ​

Console commands and scheduled tasks can start background work by passing their ctx to laravel.Background, as handlers call r.Background. When the command returns, Laravel waits for the background work to finish before the process exits. For example, this command announces a post to a webhook in the background:

go
package commands

import (
	"context"

	laravel "go.laravel.com"
	"go.laravel.com/console"
	"go.laravel.com/httpclient"
	"go.laravel.com/model"

	"app/models"
)

// AnnouncePost announces a published post.
type AnnouncePost struct{}

func (*AnnouncePost) Name() string        { return "posts:announce" }
func (*AnnouncePost) Description() string { return "Announce a post to the newsletter service" }

func (*AnnouncePost) Arguments() []laravel.Argument {
	return []laravel.Argument{
		{
			Name:        "ID",
			Description: "The ID of the post to announce",
			Required:    true,
		},
	}
}

func (*AnnouncePost) Run(ctx context.Context, c *console.Console) error {
	post, err := model.Find[models.Post](ctx, c.Args[0])
	if err != nil {
		return err
	}

	laravel.Background(ctx, func(ctx context.Context) error {
		_, err := httpclient.JSON(map[string]any{"post_id": post.ID, "title": post.Title}).
			EnsureSuccessful().
			Post(ctx, "https://example.com/webhooks/announcements")

		return err
	})

	c.Successf("Announcing %q.", post.Title)

	return nil
}

Laravel waits up to SERVER_SHUTDOWN_TIMEOUT (20 seconds by default), then cancels the context of any work still running. Background work's errors and panics are logged without changing the command's exit status.

Testing commands ​

To test a command, build a test client with laraveltest.New, then pass the command line (the part after laravel) to its Command method:

go
package feature_test

import (
	"testing"

	"go.laravel.com/date"
	"go.laravel.com/db"

	"app/tests"
)

func TestPruningDeletesOnlyStaleDrafts(t *testing.T) {
	client := tests.New(t)
	now := date.Now(client.Context())

	err := db.Table("posts").Insert(client.Context(),
		db.Values{"title": "Old draft", "updated_at": now.AddDate(0, -2, 0)},
		db.Values{"title": "Older draft", "updated_at": now.AddDate(0, -3, 0)},
		db.Values{"title": "New draft", "updated_at": now},
	)
	if err != nil {
		t.Fatal(err)
	}

	client.Command("posts:prune --days=30").
		AssertSuccessful().
		AssertErrorOutputContains("Deleted 2 drafts.")

	client.AssertDatabaseMissing("posts", db.Values{"title": "Old draft"})
	client.AssertDatabaseHas("posts", db.Values{"title": "New draft"})
}

The command runs in the test's process with the test client's database, so it sees the rows the test created. Laravel captures standard output and standard error separately. Results from Line and Table go to standard output (AssertOutputContains), while messages, such as those from Info, Success, Warn, and Error, and the error Run returns go to standard error (AssertErrorOutputContains). Use AssertOutputMissing, AssertErrorOutputMissing, and AssertNoOutput to check for absent output, and AssertExitCode or AssertFailed to check the exit status.

Command splits the command line on spaces, and quotes group words into one argument. To pass exact argument strings, use CommandArgs:

go
client.CommandArgs([]string{"posts:publish", "42", "--force"}).AssertSuccessful()

To test prompts, pass a laraveltest.Answer for each question, in the order the command asks them:

go
client.Command("user:create",
	laraveltest.Answer("What is the user's name?", "Taylor"),
	laraveltest.Answer("What is their email address?", "taylor@laravel.com"),
	laraveltest.Answer("Choose a password", "secret-password"),
	laraveltest.Answer("Create the user?", "yes"),
).AssertSuccessful()

Answer a MultiChoice with the choices separated by commas, such as "admin, editor", a Select or MultiSelect with the items' labels, such as "Staging", and a multiline prompt with the lines joined by \n. The test fails when the command asks a question that the next answer isn't for, or never asks a question that you answered. Without any answers, each prompt takes its default, as with -n.

To test signal traps, send a simulated signal with laraveltest.Signal:

go
client.Command("posts:prune", laraveltest.Signal(os.Interrupt)).
	AssertExitCode(130).
	AssertErrorOutputContains("Stopped.")

警告

Commands do their real work in tests. For example, running key:generate without --show writes your .env file. serve doesn't return until its context ends, so test your routes with HTTP tests instead.