# Laravel for Rust on the mx Stack: the laravel-rust Recipe, Containers, and Verified Gotchas

URL: https://mechcrate.dev/docs/corpus/architecture/laravel-rust-on-mx/
Source: docs/development/laravel-rust-on-mx.md

---

Laravel for Rust is "Laravel, reimagined in Rust": a full-stack framework built
on Axum and Tokio that ships routing, middleware, sessions, an ORM, forward-only
migrations, queues, scheduling, mail, broadcasting, durable workflows and testing
helpers, with an Inertia v3 + React + TypeScript + Tailwind v4 starter. It is MIT
licensed and published on laravel.com.

This document covers how it fits the mx stack through the `laravel-rust` recipe,
what was measured when the recipe was proven on 2026-12-04, and the operational
facts that are easy to get wrong. It does **not** restate the framework's API.
Section 8 says where the authoritative, version-matched API docs live.

**Maturity warning.** The framework is in beta. The docs say "Releases before
1.0 may include breaking changes to APIs and configuration", and Cargo treats
each 0.x minor as incompatible. Versions measured here: `laravel-rust` 0.2.0,
Laravel CLI 0.5.0, minimum Rust 1.99.

## 1. When to pick it

| You want | Use |
|---|---|
| A full-stack app with Laravel's conventions (resource handlers, models, queues, mail, auth) and Rust's runtime profile | `laravel-rust` |
| The mature Laravel ecosystem today: Filament admin, Horizon, the PHP package world | `laravel` (PHP, Octane) |
| An API-only Rust service where you choose every layer yourself | `rust-api` (Actix-web + SQLx, hexagonal) |
| Rust on both sides of the wire, with server-rendered components | `rust-leptos` |

Reasons to hold back: it is beta software, its frontend toolchain (Vite Plus) is itself new, and the PHP ecosystem's
packages do not exist for it. Reasons to reach for it: one static-ish binary
that serves HTTP and runs every console command, compile-time checked models
and requests, and a scaffold that ships agent instructions and eight skills
written for coding agents.

The vendor's benchmark numbers on the landing page were measured by the vendor
on Laravel Cloud. They were not reproduced here.

## 2. What the scaffolder produces

`laravel new <name> --rust` (non-interactive with the flag) downloads the starter
app, writes `.env` with a fresh `APP_KEY`, installs npm dependencies and compiles
the app. There are no other Rust-specific flags in CLI 0.5.0: the starter kit is
fixed (Inertia + React).

Key facts about the generated app, read from the generated files:

- **`Cargo.toml`**: package named after the directory, `edition = "2024"`,
  `rust-version = "1.99"`, and one framework dependency:
  `laravel-rust = { version = "0.2", features = ["database-postgres", "redis", "sqs"] }`.
  The library crate is always named `app`; rename the package, never the lib.
- **`.cargo/config.toml`**: `build-dir = "{cargo-cache-home}/build/laravel-rust"`.
  Intermediate build output goes to `$CARGO_HOME/build/laravel-rust`, shared by
  every Laravel for Rust app on the machine. Final binaries still land in
  `target/`. A bare `cargo clean` wipes the shared cache for all of them.
- **`src/main.rs`**: `app::configure().run()`. With no arguments the binary
  serves HTTP; with a command name it runs that console command.
- **`src/app.rs`**: the one place the application is assembled: embedded
  migrations (`laravel::db::migrations!`), auth guard, route files, the health
  route (`.health("/up")`), middleware.
- **`package.json`**: `npm run dev` runs three processes with `concurrently`:
  `dev:server` (nodemon running `cargo run`), `dev:queue` (nodemon running
  `cargo run -- queue:work`) and `dev:vite` (`vp dev`). `laravel dev` starts the
  same three. Node engines: `^22.18.0 || ^24.11.0 || >=26.0.0`.
- **Defaults in `.env`**: Postgres (`DATABASE_URL=postgres://postgres@127.0.0.1/laravel`),
  and sessions, cache and queue all on the `database` driver.
- **Agent files**: `AGENTS.md`, `CLAUDE.md` (imports it) and `.agents/skills/`
  with eight skills.

Cargo features of the framework crate (0.2.0): default `inertia` and
`minijinja`; opt-in `database-postgres`, `database-mysql`, `database-sqlite`,
`redis`, `sqs`, `s3`, `ses`, `reverb`, `search`, `opentelemetry`.

## 3. The mx recipe

```bash
mx add web --recipe laravel-rust
make dev s=web
```

The recipe follows the scaffolder-first rule the astro, nuxt and zola recipes
use: the framework's own CLI owns the app, and mx owns the infrastructure around
it. It writes exactly two files into the app.

| Installed path | Purpose |
|---|---|
| `apps/<svc>/` | whatever `laravel new <svc> --rust` produced |
| `apps/<svc>/vite.config.mx.ts` | dev-container Vite overrides (section 5) |
| `apps/<svc>/MECHCRATE.md` | stack notes; the scaffold's own README is left alone |
| `docker/dockerfiles/<svc>/app` | one Dockerfile: `frontend`, `builder`, `production`, `development` stages |
| `docker/dockerfiles/<svc>/app.dockerignore` | build-context filter scoped to that Dockerfile |
| `docker/compose/<svc>.yml`, `<svc>.dev.yml` | app service, queue worker, router labels |
| `docker/compose/{db,redis}*.yml` | shared Postgres and Redis |
| `docker/.config/.env.<svc>` | container environment |

Options: `--domain` (default `<svc>.localhost`), `--opt rust=<tag>` (default
`1.99`), `--opt node=<major>` (default `22`), `--opt init_cmd=...`,
`--opt force_init=true`.

### Optional features

Four features are off by default and chosen at install time:

```bash
mx add web --recipe laravel-rust --with scheduler,ssr,reverb,storage
```

`--with a,b` is shorthand for `--opt a=true --opt b=true`. On a terminal
`mx add` asks about each one; `--no-prompt`, a pipe, CI and agents get the
defaults. Re-running the command with a different set rewrites the infra files
and keeps the app.

| Feature | What it adds | Dev | Production |
|---|---|---|---|
| `scheduler` | `schedule:work` | a fourth process in the app container | `<svc>-scheduler` service |
| `ssr` | Inertia server-side rendering (`INERTIA_SSR=true`) | Vite renders on demand | image builds `npm run build:ssr` and runs `node bootstrap/ssr/app.js` beside the binary |
| `reverb` | Reverb WebSocket server, `reverb` Cargo feature, `BROADCAST_CONNECTION=reverb`, router host `ws.<domain>` | a process in the app container | `<svc>-reverb` service |
| `storage` | S3 emulator (`floci/floci`, the image the mx AWS lane uses), bucket bootstrap, `s3` Cargo feature, `FILESYSTEM_DISK=s3`, router host `storage.<domain>` | `storage` service | same service |

The install also declares `APP_KEY` (and the Reverb secret) in
`docker/.config/.env.secrets`; `make init`, which `make dev`, `make up` and
`make prod` run first, generates the values. No manual key step remains.

The mechanism is general and documented in `RECIPE_AUTHORING_GUIDE.md`:
options with a `prompt`, `condition` on template mappings and post-install
commands, `# mx:if NAME` / `# mx:endif` blocks inside template files, and
`post_install.secrets`.

Host prerequisites for the scaffold step: the Laravel CLI
(`curl -fsSL https://laravel.com/install.sh | sh`, which installs to
`~/.laravel/bin`) and Node. Host Rust 1.99+ is needed only to run the app
outside Docker (section 7, first gotcha).

## 4. Container design

### Development stage

`rust:<version>-bookworm` plus Node copied from the official Node image. The
source is bind-mounted, so the work happens at container start:

1. `npm install` into a container volume, when `node_modules/.bin/vp` is missing
   or `package.json` is newer than the installed tree.
2. `cargo run -- migrate --force`.
3. The scaffold's own three processes under `concurrently`: `npm run dev:server`,
   `npm run dev:queue`, and `npx vp dev --config vite.config.mx.ts`, plus
   `schedule:work` and `reverb:start` under the same nodemon rebuild loop when
   those features are on.

Four pieces of state live in volumes, not in the bind mount: `node_modules`
(native binaries differ per OS), `target/`, `$CARGO_HOME/build` (the scaffold's
shared build dir) and the cargo registry. Uploads and logs go to the app's own
`storage/` on the host.

The dev service has **no healthcheck**. `/up` is down for the length of every
recompile, and Traefik removes a container from its routing table while it is
unhealthy, which would take the Vite route down with the app.

### Production stage

```text
frontend   node:22-bookworm-slim      npm ci (or install) + npm run build  -> public/build
builder    rust:1.99-bookworm         cargo build --release                -> /out/app
production debian:bookworm-slim       binary + public/ + resources/views/ + storage/
```

- The binary is copied to `/usr/local/bin/app` and started from `WORKDIR /app`,
  because it must start in the directory holding `public/`, `resources/` and
  `storage/` (or be given `APP_BASE_PATH`).
- The package name, and so the binary name, is looked up from `Cargo.toml` at
  build time, since the app is free to rename its package.
- Runs as a non-root user. `ca-certificates` and `curl` are the only added
  packages; `ldd` on the binary lists five entries, all present in the slim base.
- The entrypoint runs `app migrate --force` and then `exec app "$@"` when
  started with no arguments; with arguments it runs that command and leaves the
  schema alone. `RUN_MIGRATIONS=false` opts out.
- The queue worker is the same image with `command: ["queue:work"]`, gated on
  the HTTP service being healthy (that service applied the migrations, and the
  default queue is a database table).

With the `ssr` feature the production stage also carries the Node binary, the
SSR bundle and a trimmed `node_modules`. The framework posts pages to
`http://127.0.0.1:13714` and offers no setting for that address (read from
`inertia-laravel-rust` 0.1.1), so the Node process has to share the app
container; the entrypoint starts it in the background before the binary. The
frontend stage scans the bundle for the packages it imports and installs only
those: 127 MB instead of the 432 MB build toolchain. Measured image: 417 MB
with SSR against 169 MB without, most of the difference being the 122 MB Node
binary and the starter page's WebGPU dependency.

`make prod s=<svc>` is the way to run this target. It takes the stack down,
builds, and starts every service the base compose files define. `make up s=<svc>`
restarts only the named service and leaves sidecars as they were.

Both compose and `make build` build from the project root, so every `COPY`
names `apps/<svc>` and the Dockerfile-scoped `app.dockerignore` keeps the
host's `target/` and `node_modules/` (about 560 MB for a fresh app) and the
app's `.env` out of the context. Measured context: 568 kB.

## 5. Vite HMR behind the mx router

This is the part that needed design work, and it applies to any Laravel Vite
setup behind a reverse proxy.

The page does not load its scripts from the app. `laravel-vite-plugin` writes
the dev server's address to `public/hot`, and the server-rendered page emits
`<script type="module" src="<that address>/@vite/client">`. Out of the box that
address is `http://localhost:5173`, which from a container means publishing a
host port, which collides as soon as a second stack starts, and which breaks
the mx rule that every URL goes through the router.

The recipe instead gives Vite its own hostname on the router:

- The dev compose override adds a second Traefik router,
  `Host(vite.<domain>)`, forwarding to Vite in the same container. No host
  port is published.
- Vite listens on port 80 in the container, the port in that origin, and the
  override maps `vite.<domain>` to `127.0.0.1` with `extra_hosts`. The app reads
  the same `public/hot` address to ask Vite to render pages when SSR is on, from
  inside the container, so one address has to work from both sides.
- It passes `MX_VITE_ORIGIN=http://vite.<domain>` to the container.
- `vite.config.mx.ts` spreads the app's own `vite.config.ts` and overrides only
  `server.host` (`0.0.0.0`), `server.port`/`strictPort`, `server.allowedHosts`
  and `server.hmr` (`host`, `clientPort`, `protocol` taken from that origin).

Three details make this work, each found by reading the plugin source:

1. **Set `hmr.host` and `hmr.clientPort`, not `server.origin`.** The plugin
   builds the `public/hot` URL from `hmr.host` and `hmr.clientPort` when they are
   set. Setting `server.origin` also changes the URL, but the plugin then narrows
   its CORS allow-list to that origin alone, and the page (on a different origin)
   can no longer load module scripts.
2. **A wrapper config is required.** The plugin's environment switches
   (`LARAVEL_SAIL`, `VITE_PORT`) only apply when the user config leaves
   `server.host` unset, and the scaffold's `vite.config.ts` sets it to
   `localhost`. There is no CLI flag for `hmr.*`.
3. **Name the service on every router.** Once one container declares two
   Traefik services, a router without an explicit
   `traefik.http.routers.<r>.service` is dropped.

No extra CORS configuration is needed: with `server.origin` left alone the
plugin's allow-list includes `APP_URL`, and a module request from the page's
origin came back with a matching `Access-Control-Allow-Origin` (measured).

## 6. What was verified (2026-12-04)

Run on macOS (Apple Silicon, OrbStack) against a scratch project created with
`mx new`, using an mx build of the recipe's branch.

| Check | Result |
|---|---|
| `mx add web --recipe laravel-rust` | scaffolded the app and installed 13 files |
| `make dev s=web`, time to `/up` = 200 through the router | 50 s (framework crates already in the registry cache) |
| `http://web.localhost/` in a browser | rendered, 0 console errors |
| `public/hot` | `http://vite.web.localhost:80` |
| Edit a React page on the host | DOM updated with no page reload (HMR through the router) |
| Edit `src/routes/api.rs` on the host | new response served 12 s later (nodemon + cargo rebuild) |
| Migrations | 9 tables created (`users`, `sessions`, `cache`, `jobs`, ...) |
| Published host ports on the app container | none |
| `npm run types:check`, `npm run check` with the overlay file present | pass |
| `cargo test` in the container | 2 tests pass; per-test database copies were created without extra grants |
| Production build (cold) | 1 min 40 s, image 169 MB |
| `make prod s=web` after `make dev`, all features on | 1 min 48 s; app, queue, scheduler, Reverb, storage all running |
| APP_KEY | generated by `make init` with no manual step |
| SSR, dev and production | server-rendered markup in the HTML; production SSR health endpoint 200 |
| Reverb, dev and production | WebSocket handshake through `ws.web.localhost` returns 101 |
| Storage | bucket created on start; a route calling `storage::put` then `storage::get` round-tripped a file, visible with `aws s3 ls` |
| Scheduler, dev and production | `Running scheduled tasks every minute` |
| `mx add` prompts on a pseudo-terminal | four questions asked, answers applied |
| Production container | non-root, `/up` 200, home 200, hashed asset 200, wrong `Host` header 400 |
| Queue worker service | `Processing jobs from database:default` |

The recipe's conformance tests pin the wiring: the Vite router and
`MX_VITE_ORIGIN` agree, routers name their services, no app port is published,
the Dockerfile-scoped ignore file is installed, the container binds `0.0.0.0`,
both entrypoints migrate first, the features are off by default and leave no
marker behind, each feature brings exactly its own wiring, and the compose
context with every feature on validates in both shapes.

## 7. Gotchas, each one hit or confirmed

1. **`laravel new` compiles on the host and fails after doing all the useful
   work.** With host `rustc` 1.93 the CLI exited non-zero with a JSON error
   listing every crate needing 1.99, but the app tree, `node_modules`, `.env` and
   `APP_KEY` were already on disk. The recipe's `init_cmd` treats that as a
   warning when `Cargo.toml` and `.env` exist, because the dev container has its
   own toolchain. A repo-pinned toolchain does not help: the scaffold runs in the
   new project's directory, where the rustup default applies.
2. **The server binds `127.0.0.1:8000` by default.** In a container the
   in-container healthcheck passes and the proxy gets nothing. Set
   `SERVER_HOST=0.0.0.0`.
3. **Migrations never run at startup, cannot roll back, and take no lock.**
   There is no `down` and no rollback command. Run `migrate --force` exactly once
   per deploy; with several replicas, one runs it. `migrate` prompts when
   `APP_ENV` is `production` or unset, hence `--force`.
4. **Production answers only the `APP_URL` host.** With `APP_ENV=production`,
   any other `Host` header gets a 400 (confirmed). `local` and `testing` skip the
   check. The health route runs before middleware and is unaffected.
5. **Forwarded headers are ignored until proxies are trusted, and that is code,
   not configuration.** There is no environment variable; add
   `middleware.trust_proxies([...])` in `src/app.rs`. Until then generated URLs
   use `http://` behind a TLS-terminating proxy.
6. **Process environment outranks `.env`.** Container env files win over the
   app's `.env`; anything they leave unset falls back to it in dev. The
   production image ships no `.env`, so `APP_KEY` must arrive through the
   environment (`base64:` plus 32 random bytes, the same shape as Laravel PHP).
7. **`npm ci` cannot be used on a volume-mounted `node_modules`.** It starts by
   deleting the directory, which is a mount point. The dev entrypoint uses
   `npm install`.
8. **`/up` does not check the database.** It reports that the app booted. Do
   not use it as a dependency health signal.
9. **`make up` after `make dev` reused the dev image** (mx issue
   `mech-crate-6p7`: both targets share one image tag; since 0.1.10 `make dev`
   and `make up` build before starting, and `make up` no longer inherits the
   saved dev override). `make prod` is still the one command that switches the
   whole stack, sidecars included.
10. **A worker runs the code it was compiled with.** Rebuild and restart the
    queue service with every deploy. Renaming a job struct orphans queued jobs
    unless the job carries an explicit name.
11. **`cargo clean` in one app clears the build cache of every Laravel for Rust
    app on that machine** (the shared `build-dir`).

12. **MinIO's Docker images are no longer published** (`minio/minio` and
    `minio/mc` fail to resolve on Docker Hub and Quay as of 2026-12-04). The
    storage feature uses the Floci emulator instead. Its image has bash but no
    curl or wget, so the healthcheck is a bash `/dev/tcp` connect.
13. **Reverb is documented as a local development server.** The recipe runs it
    in the production compose target for parity, but a real deployment should
    use a managed WebSocket service. The scaffold ships no Echo client code.
14. **A dependency's Cargo feature cannot be switched on from the environment.**
    `reverb` and `s3` are features of the app's `laravel-rust` dependency, so
    the install edits that one line of the app's `Cargo.toml`.

## 8. Where the real API documentation lives

Do not write Laravel for Rust code from memory of Laravel PHP or of Axum. The
framework's API is young and changes between minors.

- The `laravel-rust` crate **bundles its complete Markdown documentation** for
  the exact version an app depends on (69 guides in 0.2.0, about 1.5 MB), in the
  `docs/` directory of the crate source under the cargo registry. The scaffold
  ships a helper that prints the path:
  `.agents/skills/writing-laravel-rust-apps/scripts/docs-path.sh`.
- Start at `documentation.md` (table of contents). `upgrade.md` lists the
  changes per minor version.
- The scaffold's `AGENTS.md` states the house conventions (lean resource
  handlers with the standard CRUD verbs, a model's factory and policy in the
  model's file, feature tests through `app.get`/`app.post` with subsystem fakes)
  and maps eight skills to topics: app structure, database and models,
  validation, auth, queues and workflows, testing, the Inertia frontend, and
  upgrading.

For orientation only, these are idioms copied from the generated app, not a
reference:

```rust
// src/routes/api.rs
pub fn routes(route: &mut Router) {
    route.get("/version", async || Json(json!({ "laravel": laravel::VERSION })));
    route.fallback(async || laravel::abort(404));
}

// src/http/handlers/welcome.rs: an Inertia page
pub async fn show() -> Page {
    inertia::render("Welcome", props! { laravelVersion => laravel::VERSION })
}

// tests/api.rs: every test gets its own application and database copy
#[laravel::test]
async fn the_api_reports_laravels_version(app: Application) {
    app.get("/api/version").await.assert_ok();
}

// database/migrations/<timestamp>_create_users_table.rs: forward-only
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("users", |table| {
            table.id();
            table.string("email").unique();
            table.timestamps();
        })
        .await
}
```

## 9. Command reference

| Task | On a host | In the mx dev container |
|---|---|---|
| Dev processes | `laravel dev` | `make dev s=<svc>` |
| Console command | `laravel <command>` | `make exec s=<svc> c="cargo run -- <command>"` |
| Migrate | `laravel migrate` | runs at container start |
| Routes | `laravel route:list` (`-v`, `--json`) | as above |
| Tests | `cargo test` (name filter: `cargo test posts`) | `make exec s=<svc> c="cargo test"` |
| Rust lint and format | `cargo clippy --all-targets`, `cargo fmt` | same, through `make exec` |
| Frontend checks | `npm run types:check`, `npm run check` | same |
| Production binary | `./<app> migrate --force`, `./<app>`, `./<app> queue:work` | the image's entrypoint and the `-queue` service |
| New key | `./<app> key:generate --show` | generated by `make init`; blank `APP_KEY=` in `.env.secrets` to rotate |
| Production mode | build, then run the binary | `make prod s=<svc>` |

Related corpus documents: `mx-app-playbook.md` (project anatomy and the
always-use-the-router rule), `mx-recipes-and-build.md` (recipe lifecycle and
image builds), `RECIPE_AUTHORING_GUIDE.md` (scaffolder-first recipes),
`appendix-laravel.md` (Laravel PHP idioms, for contrast).
