Article

Laravel Rust in Practice: Build an API, Validate Requests, and Deploy It

Laravel Rust in Practice: Build an API, Validate Requests, and Deploy It

Build your first API with the Laravel Rust beta. Learn typed validation, PostgreSQL models, async queues and workflows, and how to measure whether a Rust pilot is worth shipping.

15 min readLanguage: EN EnglishFree0 claps0 comments
Engineering ArticlesAPILaravelPostgreSQLQueuesRust
Reading options

Laravel released the first beta of Laravel Rust on December 1, 2026. The framework brings Laravel's conventions for routing, validation, database models, authentication, queues, and testing to applications compiled with Rust. It runs on Axum and Tokio. If you've built APIs with Laravel PHP, you'll recognize the steps between receiving a request and writing to the database. The main difference is how much of that contract you express through Rust types. Laravel Rust release announcement

In this guide, you'll build and exercise two endpoints for a report service. The first checks that the API is reachable. The second demonstrates what happens when the framework validates JSON before an endpoint runs. Then we'll design the database and background jobs for a version that generates downloadable CSV reports.

What changes for a Laravel PHP developer?

Concern Laravel PHP Laravel Rust
Routing Route definitions point to closures or controllers Route functions register async handlers with a Router
Request validation Form Requests typically define rules in arrays Input structs declare field types, rules, and authorization
Data access Eloquent models and relationships Rust model structs, typed queries, and explicit relationship loading
Development tooling Composer and Artisan Cargo and the Laravel CLI
Deployment PHP runtime with an application server or worker A compiled Rust executable, with frontend output and dependencies as required

Think about Option<String> for an optional report title and an enum for report states such as Queued, Running, Completed, and Failed. Rust makes you handle the cases you model. The database still owns invariants that depend on multiple processes, such as whether two requests can create the same report. A unique constraint can enforce that rule even when requests reach different replicas.

Async I/O lets Tokio run other tasks while a handler waits for a database response or an HTTP call. A slow SQL query still holds a connection, and a CPU-intensive CSV transformation still consumes CPU. Asynchronous execution helps you use threads efficiently. The next limits are often pool size, query design, and how much work you accept at once. Laravel Rust installation and architecture overview

1. Create a Laravel Rust project

Install Git, Node.js LTS for the starter frontend, and Rust 1.99 or later. If you already use rustup, run rustup update stable and confirm your toolchain with rustc --version. Install the Laravel CLI using the instructions for your operating system, then open a new terminal so it picks up the CLI on your path. Official installation guide

laravel new report-service --rust
cd report-service

Keep PostgreSQL for this walkthrough. Set the connection in the generated .env to use a local database and a role you control. Change the example username and password to match your development setup.

DB_CONNECTION=postgres
DATABASE_URL=postgres://report_app:local_password@127.0.0.1:5432/report_service

Create the database or give the development role permission to create it. Then run the starter migrations and start the app.

laravel migrate
laravel dev

laravel dev starts the application, a queue worker, and the frontend development server. The backend is available at http://127.0.0.1:8000 with the default configuration. If startup fails at the migration step, check PostgreSQL connectivity, the database name, the role's privileges, and the URL encoding of any special characters in the password. Laravel Rust development guide

The starter sets up separate web and API route modules. Check that src/app.rs registers routes::api::routes using .api(routes::api::routes). Routes in that module use the /api prefix by default. Laravel Rust routing

2. Add a route and a typed JSON endpoint

In src/routes/api.rs, add these definitions. If the starter already has a routes function, add the two registrations to it and retain any existing routes.

use laravel::prelude::*;

#[laravel::input]
#[validate(anyone)]
pub struct PreviewReport {
    #[validate(required, max_length(120))]
    pub title: String,
}

pub fn routes(route: &mut Router) {
    route.get("/status", async || "report-service ready");
    route.post("/reports/preview", preview_report);
}

async fn preview_report(Valid(input): Valid<PreviewReport>) -> String {
    format!("Preview requested for: {}", input.title)
}

The POST returns a plain-text acknowledgment so the example can focus on JSON input. The input macro defines how the request becomes a Rust struct, the field rules reject invalid titles, and Valid<PreviewReport> supplies a validated value to the handler. The explicit anyone declaration is appropriate for this demonstration because it only echoes the incoming title. Creating a real report should require authentication and permission to read the underlying data. Laravel Rust validation

Run these commands from a second terminal.

curl -i http://127.0.0.1:8000/api/status

curl -i http://127.0.0.1:8000/api/reports/preview \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{"title":"December sales"}'

curl -i http://127.0.0.1:8000/api/reports/preview \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{"title":""}'

The status route and the valid preview should return 200 OK. The empty title should produce a 422 validation response, with a field error for title. Content-Type tells Laravel how to read the request body, and Accept tells it to return JSON when validation fails. The plain-text success response comes from the handler's return type. The status route is a basic reachability probe. A production readiness check can also verify critical dependencies with short timeouts.

3. Persist a report request in PostgreSQL

A production endpoint can create a report record and return 202 Accepted with its ID and status URL. The client can poll that URL while the worker generates the file. Give the request and the report separate lifecycles so the browser never has to hold a connection open through CSV generation.

Laravel Rust defines models as structs and supports relationships declared on those models. You select the relationships the query needs up front. For a list of reports with owner details, load owners in bulk. For a job that only needs report IDs and date ranges, select the fields it uses. Pagination, query shape, and indexes matter just as much as the runtime. Laravel Rust model relationships

For the first persistence migration, give each report a stable ID, a tenant ID, an owner ID, the title and date range, a status, and timestamps. Add the output object's storage key once generation finishes. If the main screen lists reports newest first for one tenant, consider an index on (tenant_id, created_at DESC, id DESC) and confirm the plan against realistic data.

Separate three layers of correctness.

  • Validate the request. Check the title, require the necessary dates, and reject a date range larger than the service can process.
  • Authorize the operation. Scope access to the tenant and verify that the caller can export the requested dataset. Repeat the access check when returning status or issuing a download link.
  • Enforce invariants in PostgreSQL. Use a unique constraint for an idempotency key scoped to the tenant. Save a hash of the normalized request so a repeat with the same parameters can return the original report ID and a conflicting reuse can return 409 Conflict.

Treat a duplicate caused by two concurrent requests as a normal outcome. Catch the unique-constraint conflict and fetch the original record. A separate “does this key exist?” read cannot guarantee uniqueness when two writers run at once. Laravel Rust database migrations

4. Decide between a queue job and a durable workflow

For a small CSV export, a single queue job can read the source rows in batches, write the file to object storage, and mark the report complete. Send the report ID in the job payload. Keeping a copy of every source row in the payload increases queue size and makes retries harder to reason about. Laravel Rust queues

A deployment can stop a worker after it uploads the file but before it updates PostgreSQL. A retry should be safe at that boundary. Use a stable output key for each report and use the report record to track completion. If you also email the user, use the provider's idempotency key when available, or store and reconcile notification attempts. Treat “the provider may have accepted this request before the connection failed” as its own outcome.

Another boundary is the transition from creating a report to dispatching the job. If the database commit succeeds and the broker is unreachable, you'll have a queued report with no worker message. An after-commit dispatch keeps a worker from seeing uncommitted data. A transactional outbox closes the separate gap between committing and dispatching: write the report and an outbox entry together, then have a relay deliver entries with retry and deduplication. GAUAB's transactional outbox guide

Consider a durable workflow when the report grows into a multi-step process. For example, a heavy export may split by date range, create parts in parallel, assemble the result, and wait for an approval before sending a notification. Persisting workflow progress gives later workers a place to resume. Each external side effect still needs a retry strategy because an object store, mail provider, and database cannot all commit the same operation atomically. Laravel Rust workflows

5. Test the cases the compiler cannot prove

The compiler checks Rust types and handler signatures. Use HTTP and integration tests for behavior that depends on input, customer data, or timing. Run the persistence tests against the same database engine you deploy, especially when they exercise transaction isolation or unique constraints. Laravel Rust testing

Test Expected behavior
Preview with a valid title 200 with the supplied title in the response
Preview with a missing, empty, or oversized title 422 with a title validation error
Create the same report concurrently with the same idempotency key One report is created and both requests resolve to its ID
Reuse the key with a different date range 409 and the first report is preserved
Request a report from a different tenant The request receives the application's access-denial response
Stop the worker after upload and before status update Retrying completes the report using the same logical output
Delay PostgreSQL or the object store Timeouts are bounded and the failure can be observed and retried

Run cargo fmt --check, cargo clippy, and cargo test in CI. If you ship frontend assets, include their build in CI as well. An approval or quota rule deserves its own test even if it uses valid, well-typed input.

6. Deploy and measure with your own workload

Laravel Cloud supports the Rust runtime. For a self-managed deployment, build a release executable for the target environment, provision the runtime and frontend assets your app needs, and run the web process and its queue workers under a supervisor or orchestrator. Configure runtime secrets outside the build, run database migrations as a controlled release step, and give workers enough time to finish or safely reschedule active jobs during shutdown. Laravel Rust deployment

Budget database connections across all replicas, including workers, schedulers, and migrations. For example, six web replicas with pools of 15 and four worker replicas with pools of 10 can reserve up to 130 connections before administrative capacity. If the database is already busy, raising HTTP concurrency can increase wait time in the pool. Monitor pool wait, query duration, queue age, job retries, and p95/p99 latency together so you can locate the bottleneck.

Laravel's own benchmark measured 1,774 successful requests per second for Laravel Rust and 97 for Laravel PHP in their best 10-second windows without failures during a traffic ramp. The workload was two read endpoints against a small MySQL dataset. At a steady 50 RPS, p95 latency was 93 ms versus 111 ms, and peak observed memory was 16 MB versus 134 MB in the reported table. The two tests answer different questions: the ramp shows how much load that deployment could accept, while the steady run shows its resource use and latency at a rate both handled. Laravel's benchmark and methodology

For a production decision, reproduce the traffic mix you actually run. Include realistic data volume, authentication, writes, concurrent exports, and the dependency latency you see in production. Record the highest sustained throughput within your latency and error budgets, alongside memory, database load, and deployment time. The cost calculation should also include the time your team needs to build, review, and operate Rust code.

Where to start if you already run Laravel PHP

A read-heavy endpoint or a background export worker makes a practical first pilot. It gives the Rust service a narrow contract and lets you compare the same payloads, database behavior, and operating cost across implementations. If your PHP application owns the report schema, keep one migration owner. If both apps need to exchange jobs, define a versioned message contract and test it with both runtimes. Sharing a broker alone gives you no guarantee that the two frameworks can deserialize each other's native job payloads.

If you need a package that currently exists in Composer, include its replacement cost in the pilot. You may find that your bottleneck is a missing PostgreSQL index or that a better batching strategy already meets the target. Laravel Rust makes the most sense when a measured constraint, a clearly owned service, and the team's ability to maintain Rust point in the same direction. For a wider framework comparison, see GAUAB's Laravel Go vs. Laravel Rust guide.

Frequently asked questions

Does Laravel Rust run an existing Laravel PHP application?

Laravel Rust applications are written and compiled as Rust. You can retain an HTTP contract, data model, or business rule from a PHP application, then implement it in Rust and verify parity with contract tests. Composer packages remain PHP dependencies.

Do I need PostgreSQL or React to use Laravel Rust?

This tutorial uses PostgreSQL and the scaffold's frontend tooling. The framework also documents support for MySQL, MariaDB, and SQLite. You can build a JSON API with a separate frontend, or use Laravel Rust's Inertia integration for an application with server-side routes and a JavaScript interface. Laravel Rust documentation

Is the beta ready for a critical production migration?

Start with a staging service and decide based on your error budget, beta upgrade testing, operational support, and rollback plan. A good first cutover has one clear owner, a contract clients can test, and a way to return traffic to the existing service.

Featured Articles

20 minFree
EN

Build a Task CRUD API in Laravel Rust and Laravel PHP with PostgreSQL

Build the same PostgreSQL-backed task API in Laravel PHP and Laravel Rust. Get complete code for all five CRUD endpoints, a shared smoke test, and a side-by-side comparison of the two implementations.

Engineering ArticlesAPILaravelPHP
0 claps
Read
Laravel Rust vs. Laravel PHP: Code, Performance, and Migration Trade-offs
EditorialEN
17 minFree

Laravel Rust vs. Laravel PHP: Code, Performance, and Migration Trade-offs

Compare Laravel Rust and Laravel PHP through the same API endpoint, Eloquent and typed queries, queues, deployment, and Laravel’s benchmark. Learn when to use Octane, stay on PHP, or move one workload to Rust.

Engineering ArticlesLaravelPerformancePHP
0 claps
Read
Laravel Go and Laravel Rust: A Practical Guide for PHP Teams
EditorialEN
7 minFree

Laravel Go vs. Laravel Rust: An Engineering Guide for PHP Teams

A hands-on comparison of Laravel Go, Laravel Rust, and PHP, with route examples, benchmark analysis, and a production migration plan.

Engineering Articles
0 claps
Read

Comments

0 comments

No approved comments are visible yet. New community replies may wait for moderation.