Console Commands
- Introduction
- Complete Example: A Validating Command
- Tinker (REPL)
- Available Commands
- Generating Code
- Writing Commands
- How Commands Run
- Not Yet Available
Complete Example: A Validating Command
Add this file to a Blog application:
// app/Commands/GreetDemo.cs
using DotBlaze;
namespace Blog.Commands;
public class GreetDemo : Command
{
public override string Signature => "demo:greet {name} {--times=1}";
public override string Description => "Print a greeting one to five times.";
public override Task<int> Handle()
{
if (!int.TryParse(Option("times"), out var count) || count is < 1 or > 5)
{
Error("--times must be between 1 and 5.");
return Task.FromResult(1);
}
for (var index = 0; index < count; index++)
Line($"Hello, {Argument("name")}.");
return Task.FromResult(0);
}
}Run dotblaze demo:greet Ada --times=2: two Hello, Ada. lines and exit code 0. --times=abc returns 1 with the validation message. dotblaze demo:greet --help shows usage. Runtime fallback: dotnet run -- demo:greet Ada; make:* generators themselves belong to the CLI rather than the application's runtime command registry.
Introduction
Laravel ships with Artisan, a command line interface that runs inside your application. DotBlaze takes the same approach: the commands are built into the application, and you run them by passing the command name to your app, either directly or through the dotblaze tool.
The dotblaze Tool
dotblaze is a dotnet tool (see Installation for how to install it). Run it anywhere inside your application folder; it finds the nearest .csproj that references DotBlaze by searching upward from the current directory.
| Command | What it does |
|---|---|
dotblaze new Blog | Creates a new application (runs dotnet new dotblaze-app -n Blog -o Blog). |
dotblaze serve | Runs the web server (dotnet run). Extra arguments go to dotnet run. |
dotblaze serve --watch | Watches files and rebuilds/restarts (dotnet watch --no-hot-reload --project <app.csproj> run), including Blade changes. Remaining arguments are forwarded after run; arguments after -- belong to the app. See Hot Reload. |
dotblaze make:... | Generates code, see Generating Code. These run in the tool itself and do not build your app. |
dotblaze <command> | Anything else runs in your application: dotblaze migrate is dotnet run -- migrate. |
Running Commands
With the tool:
dotblaze list
dotblaze migrateWithout it, put the command after --, so dotnet run passes it to your application:
dotnet run -- list
dotnet run -- migrateA published application takes the command as its first argument:
dotnet Blog.dll migratelist shows every command: the built-in ones, your own, and (through the tool) the generators. --help after a command name shows its arguments and options:
dotblaze queue:work --helpPassing Options
Options use the --name=value or --name value form; an option without a value is a flag. Other arguments are positional:
dotblaze queue:work --queue=emails,default --sleep=5
dotblaze migrate:fresh --seed
dotblaze queue:retry 12Unknown options, missing arguments, and extra arguments print the usage and exit with 1.
Tinker (REPL)
Tinker is an interactive C# console with your application loaded, like php artisan tinker. You can use your models, facades, and services in it. It ships as a separate package, because it brings the C# compiler (Roslyn) with it:
dotnet add package DotBlaze.Tinkerdotblaze tinker> await Post.Query().Count()
= 18
> var user = await User.Find(1);
> user.Email
= "ada@example.com"
> if (user is not null) {
* Console.WriteLine(user.Name);
* }
Ada
> exitHow Tinker works:
- An expression without a semicolon prints its value. Strings are shown quoted, and models and collections as JSON, with hidden attributes left out.
- A statement or declaration ending in
;prints nothing. Its variables, methods, classes, andusingdirectives stay available for the rest of the session. awaitworks at the top level.- Code that is not finished yet, such as an open
{, continues on the next line, shown as*. - An error prints the compiler message or the exception, and the session keeps its state.
The namespaces System, System.Linq, System.Collections.Generic, System.Threading.Tasks, System.Text, and DotBlaze are imported, plus every namespace of your application and its packages. A type such as Post therefore needs no using.
The code runs in one service scope for the whole session, like a command does. Saving models, sending mail, and dispatching jobs all happen for real, in the database the configuration points at.
To run code without the prompt, pass it with --execute, or pipe it in. The exit code is 1 if the code failed:
dotblaze tinker --execute="await User.Query().Count()"echo 'await Cache.Forget("post-stats")' | dotblaze tinkerAvailable Commands
Database Commands
| Command | Description |
|---|---|
migrate | Run pending migrations. --seed runs DatabaseSeeder afterwards; --seeder=Name picks another seeder. |
migrate:rollback | Roll back the last batch of migrations. |
migrate:reset | Roll back all migrations. |
migrate:fresh | Drop all tables on the default connection and run all migrations again. Accepts --seed and --seeder=Name. |
migrate:status | Show which migrations have run, and in which batch. |
db:seed | Run DatabaseSeeder, or another seeder with --class=Name. |
db:check | Compare your models with the database schema and list the differences. |
NOTE
To choose a seeder, db:seed uses --class=Name, while migrate --seed and migrate:fresh --seed use --seeder=Name. This is intentional and the same as in Laravel.
See Migrations and Seeding.
Queue Commands
| Command | Description |
|---|---|
queue:work | Process jobs until stopped. Options: --queue=a,b (queues in priority order, default default), --connection=name, --sleep=3 (seconds to wait when the queues are empty), --stop-when-empty, --memory=MB, --max-jobs=N, --max-time=seconds (exit after a limit; memory exits with 12), and --tries, --backoff, --timeout (defaults for jobs that set none). |
queue:manager | Run and balance many queue:work processes from queue.manager in config/Queue.cs, like Horizon. See The Queue Manager. |
queue:manager:status | Show the running queue managers, their workers, and waiting jobs. |
queue:manager:terminate | Stop the queue managers after their workers finish the current job (run after a deploy). |
queue:failed | List failed jobs. |
queue:retry <id|all> | Push one failed job, or all of them, back onto the connection each failed on. A missing or invalid id prints the usage and exits with 1. |
queue:flush | Delete all failed jobs. |
queue:prune-batches | Delete finished batches older than --hours=24; --unfinished=72 also deletes unfinished ones older than that. |
The dashboard packages add their own commands:
| Command | Description |
|---|---|
horizon:clear | Delete the jobs recorded by Horizon. |
telescope:prune | Delete Telescope entries older than --hours=24. |
telescope:clear | Delete every Telescope entry. |
pulse:check | Record this server's CPU, memory, and disk usage for Pulse until stopped (--once for one reading). |
pulse:clear | Delete everything Pulse recorded. |
queue:work checks the queues in the order given and always drains the first one before moving to the next. Pressing Ctrl+C (SIGINT) or sending SIGTERM lets the current job finish before the worker stops. In production, run workers under a process supervisor; see Deployment and Queues.
Schedule Commands
| Command | Description |
|---|---|
schedule:run | Run the scheduled tasks that are due. Call it every minute from cron. |
schedule:work | Run the scheduler every minute until stopped (instead of a cron entry). |
schedule:list | List the scheduled tasks, their cron expressions, and when each runs next. |
schedule:test <task> | Run one task now, by its number in schedule:list or its name. |
Auth Commands
| Command | Description |
|---|---|
tokens:prune-expired | Delete API tokens that expired more than --hours=24 ago. |
Maintenance Commands
| Command | Description |
|---|---|
down | Put the application into maintenance mode. Options: --secret=, --with-secret, --retry=, --refresh=, --redirect=, --render=, --status=503. |
up | Bring it back up. |
Route Commands
| Command | Description |
|---|---|
key:generate | Write a new APP_KEY to .env (from .env.example if there is no .env yet). Refuses to replace a key without --force; --show only prints a key. See Encryption. |
route:list | List all registered routes with their HTTP methods, URI, name, controller action, and middleware. |
Cache Commands
| Command | Description |
|---|---|
cache:clear [store] | Flush a cache store (default: cache.default). |
Generating Code
The make:* generators write a new file into the conventional folder, with the namespace taken from your project (its <RootNamespace>, or the .csproj file name). A name with slashes creates subfolders and namespaces: dotblaze make:controller Admin/DashboardController writes app/Http/Controllers/Admin/DashboardController.cs in namespace Blog.Controllers.Admin.
Generators never overwrite an existing file unless you pass --force (-f).
Core generators run in the CLI. Package-specific generators are discovered from installed packages and forwarded to the application, so they require a buildable app. make:agent, make:agent-middleware, and make:tool only appear and work after installing DotBlaze.AI. The same rule applies to third-party generators; package authors use GeneratorCommand, not a hard-coded CLI entry.
| Command | Creates | Options |
|---|---|---|
make:controller Name | app/Http/Controllers | --resource (-r): the seven resource actions; --model=Post: actions take a Post (inferred from PostController when app/Models/Post.cs exists). |
make:factory Name | database/factories | --model=Post (inferred from the name otherwise). |
make:model Name | app/Models | --factory: also a factory. --migration (-m): also a create_<table>_table migration. |
make:migration name | database/migrations | --create=table, --table=table. See Migrations. |
make:seeder Name | database/seeders | |
make:request Name | app/Http/Requests | |
make:middleware Name | app/Http/Middleware | --parameters: implements IParameterizedRouteMiddleware (role:admin,editor). |
make:provider Name | app/Providers | |
make:agent Name [--structured] | app/Ai/Agents | Named agent; requires the optional AI SDK package. --structured adds a result record and a typed Ask method. |
make:agent-middleware Name | app/Ai/Middleware | A DelegatingChatClient to return from an agent's Middleware(). |
make:tool Name | app/Ai/Tools | Described function handler for registration with AIFunctionFactory.Create. |
make:job Name | app/Jobs | --sync: not queued (no IShouldQueue). |
make:event Name | app/Events | |
make:listener Name | app/Listeners | --event=Name (required), --queued. |
make:live Name | app/Live + resources/views/live | The class and its view; adds @using <App>.LiveComponents to _ViewImports.cshtml. See Live Components. |
make:mail Name | app/Mail | --queued: implements IShouldQueue. See Mail. |
make:notification Name | app/Notifications | --sync: not queued. See Notifications. |
make:policy Name | app/Policies | --model=Post: the model (inferred from PostPolicy). See Authorization. |
make:command Name | app/Commands | --command=app:name: the command name; by default SendEmailsCommand becomes app:send-emails. |
make:auth | Login, registration, password reset, email verification | See below. |
Requests are put in the Blog.Requests namespace and controllers in Blog.Controllers (not Blog.Http.*), so that a namespace named Http does not hide the Http facade.
Authentication Scaffolding
dotblaze make:auth adds the authentication code from the sample blog, which is covered by its tests: login (with "remember me" and login throttling), registration, logout, password reset, and email verification:
app/Http/Controllers/AuthController.cs,PasswordResetController.cs, andEmailVerificationController.csapp/Http/Requests/LoginRequest.cs,RegisterRequest.cs,ForgotPasswordRequest.cs, andResetPasswordRequest.csresources/views/auth/Login.blade.html,Register.blade.html,ForgotPassword.blade.html,ResetPassword.blade.html,VerifyEmail.blade.html,ConfirmPassword.blade.html,TwoFactorChallenge.blade.html, and the_Field.blade.htmlpartial (Blade views)routes/auth.cs, whoseAuthRoutes.Map()is added afterWeb.Map()inRouteServiceProvider
The template's User model and migrations already have what these need (RememberToken, EmailVerifiedAt, the password_reset_tokens table). Reset and verification links are emailed, so configure mail and APP_URL.
If any of these files already exists, nothing is written unless you pass --force. Your layout is not changed; the command prints the snippet for the login, register, and logout links. After logging in, users go to / (the Home constant in AuthController). See Authentication.
Writing Commands
Generate a command with dotblaze make:command SendEmailsCommand. Any non-abstract class in your application that extends DotBlaze.Command is discovered automatically:
namespace Blog.Commands;
public class SendEmailsCommand(IQueue queue) : Command
{
public override string Signature => "mail:send {user : The user id} {--queue=default}";
public override string Description => "Send the welcome email to a user";
public override async Task<int> Handle()
{
var user = await User.Find(long.Parse(Argument("user")!));
if (user is null)
{
Error("User not found.");
return 1;
}
await queue.Push(new SendWelcomeEmail { User = user }, Option("queue"));
Info($"Queued the email for {user.Email}.");
return 0;
}
}The constructor may take services from dependency injection. Facades and models work inside Handle, as in a controller. Handle returns the exit code: 0 for success. Two commands with the same name stop the application at startup with an error naming both classes.
Closure Commands
A small command does not need a class. Define it with a closure in routes/console.cs, like Laravel's Artisan::command(). The application template includes this one, so dotblaze inspire works in a new app:
public static class ConsoleRoutes
{
public static void Map()
{
Artisan.Command("inspire", (ClosureCommand command) =>
{
command.Comment(Inspiring.Quote());
}).Purpose("Display an inspiring quote");
}
}The signature has the same syntax as a class command's, and .Purpose(...) is the description dotblaze list and --help show. The closure's parameters are filled by type and name:
| Parameter | Value |
|---|---|
ClosureCommand | The running command, Laravel's $this: Argument, Option, Flag, Line, Info, Comment, Error, Call, Out, Stopping. |
| Named like an argument or option | Its value, converted to the parameter's type (string, numbers, bool, enums, and their nullable forms). --dry-run fills dryRun; a flag fills a bool. |
CancellationToken | Cancelled on Ctrl+C or SIGTERM, like Stopping. |
| Any other type | A service from dependency injection. |
Artisan.Command("posts:count {--user= : Only this user's posts}", async (ClosureCommand command, long? user) =>
{
var query = Post.Query();
if (user is { } id) query = query.Where(p => p.UserId == id);
command.Info($"{await query.Count()} posts");
}).Purpose("Count the posts");
Artisan.Command("mail:send {user} {--queue=default}", async (ClosureCommand command, long user, string queue, IQueue jobs) =>
{
await jobs.Push(new SendWelcomeEmail { User = await User.FindOrFail(user) }, queue);
return 0;
});The closure may return nothing (exit code 0), an int exit code, a Task, or a Task<int>. A value that cannot be converted, such as --user=abc for a long?, prints the error and the usage and exits with 1. A closure command with the same name as a class command, or as another closure command, stops the command with an error naming both.
routes/console.cs runs in RouteServiceProvider.Boot, so closure commands are registered before any command runs, and the scheduler can run them with Schedule.Command("inspire").
Defining Input
The signature uses Laravel's syntax: the command name, then each argument and option in braces.
| Syntax | Meaning |
|---|---|
{user} | Required argument. |
{user?} | Optional argument. |
{user=1} | Optional argument with a default. |
{--force} | Boolean option (flag). |
{--queue=} | Option that takes a value. |
{--queue=default} | Option with a default value. |
{--F|force} | Adds the shortcut -F. |
{user : The user id} | A description, shown by --help. |
Arrays ({user*}) are not supported.
Reading Input
Argument("user") and Option("queue") return the value as a string, the default when it was not passed, or null. Flag("force") returns whether a boolean option was passed.
Writing Output
Line(text) and Info(text) write to standard output, Error(text) to standard error. There are no colors, tables, or prompts yet.
Long-Running Commands
The Stopping token is cancelled on Ctrl+C or SIGTERM. Pass it to async calls, or check it in a loop, so the command can stop cleanly:
foreach (var user in await User.All())
{
if (Stopping.IsCancellationRequested) return 1;
await SendReport(user);
}Calling Other Commands
Call(commandLine) runs another command in-process, like Laravel's $this->call(), and returns its exit code; its output goes to this command's output:
await Call("cache:clear redis");
await Call("migrate");The scheduler runs Schedule.Command(...) tasks the same way.
From controllers or services, use the Artisan facade:
using var output = new StringWriter();
var exitCode = await Artisan.Call("route:list", output);
var text = output.ToString();Artisan.Call also accepts a string array of command arguments, a separate error writer, and a cancellation token. It returns the command's exit code, preserves command validation and exception behavior, and uses a fresh service scope with a copy of the caller's context.
How Commands Run
When the first argument is a command name, Application.Create builds the application exactly as it does for the web server: .env and the config/*.cs classes are loaded, and every provider runs Register and Boot. Then, instead of starting the web server, the command runs inside its own service scope, so facades and models work as usual. Command options are not added to the application's configuration.
Because the web host is not started for a command, hosted services do not run. In particular, the in-app queue worker (queue.worker: true) never runs during a command.
The dotblaze tool forwards a command with dotnet run --project <your.csproj> -- <command>, so it builds your application first if needed. Build errors are shown and the command does not run.
NOTE
Any first argument that is not an option (--x or x=y) is treated as a command. An unknown one, such as a misspelled dotblaze migrat, prints Unknown command 'migrat'. and exits with 1 instead of starting the web server.
Exit Codes
Commands exit with code 0 on success. Some commands use other codes, which is useful in scripts and CI:
db:checkexits with1when the schema does not match the models.queue:workexits with1when a job ignores its timeout, so a process supervisor can start a fresh worker.- Bad input (unknown command or option, missing argument) exits with
1. - An unhandled exception (for example a failing migration) ends the command with a non-zero code.
The dotblaze tool returns the exit code of the command it forwarded.
Not Yet Available
There are no interactive prompts (ask, confirm), tables, or progress bars in commands yet.