Laravel Rust Best Practices
ASecurityBest practices for apps built with Laravel for Rust (the laravel-rust crate, 0.1.x). Use when writing or reviewing Laravel for Rust code — handlers, input structs, models and queries, migrations, transactions, jobs, events, the scheduler, the HTTP client, cache, config and deployment. Each rule shows the common version (usually code that compiles but behaves wrongly: a panic into a 500, data cleared by a PATCH, another user's record changed, a job lost on deploy, an HTTP 500 handled as succes...
- 2 stars
- 0 votes
- 0 copies
- 0 views
- Added December 2, 2026
Works with
Security analysis
100/100Pro scans all 19 files and shows the line behind each finding
npx -y skills add airshell/laravel-php-to-rust --skill laravel-rust-best-practices --agent claude-codeAre you the author of Laravel Rust Best Practices?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/airshell-laravel-rust-best-practices)---
name: laravel-rust-best-practices
description: Best practices for apps built with Laravel for Rust (the laravel-rust crate, 0.1.x). Use when writing or reviewing Laravel for Rust code — handlers, input structs, models and queries, migrations, transactions, jobs, events, the scheduler, the HTTP client, cache, config and deployment. Each rule shows the common version (usually code that compiles but behaves wrongly: a panic into a 500, data cleared by a PATCH, another user's record changed, a job lost on deploy, an HTTP 500 handled as success, a time test that cannot pass; a few are configuration or deploy mistakes) and the version to write. Every Rust example compiles against laravel-rust 0.1.4, and the main claims were tested on that version. Complements the seven skills a new app ships in .agents/skills/. For porting from Laravel PHP use laravel-php-to-rust; for a security audit use laravel-rust-audit; for the Rust language itself use rust-for-laravel-developers.
license: MIT
metadata:
author: airshell
version: "1.0.1"
laravelRustVersion: "0.1.x (tested 0.1.4)"
rustVersion: "1.99+"
---
# Laravel for Rust Best Practices
Best practices for apps built with [Laravel for Rust](https://laravel.com/rust) (`laravel-rust` 0.1.x). Contains 30 rules across 7 categories. Every Rust example compiles against `laravel-rust` 0.1.4, and each "Tested on laravel-rust 0.1.4" note records what a test on that version showed.
**Version 1.0.1 (December 2026).** Laravel for Rust is in beta; check APIs against the docs bundled with the version you install (`.agents/skills/writing-laravel-rust-apps/scripts/docs-path.sh`, which needs `cargo` on `PATH`; otherwise the docs are in `~/.cargo/registry/src/*/laravel-rust-<version>/docs`).
## When to Apply
- Writing handlers, input structs, models, queries, migrations, jobs, listeners, scheduled tasks or configuration in a Laravel for Rust app
- Reviewing Laravel for Rust code before it ships
- Deciding between two ways to do something the framework allows (a background task or a job, `parse` or `validate`, `Option` or `Sometimes`)
## How This Skill Fits
A new app ships seven skills in `.agents/skills/` (writing, testing, database, validation, auth, queues, Inertia) that describe how the framework works. This skill adds what they leave out: the mistakes that compile and still behave wrongly, each with the version to write and, where it matters, a test that proves the difference.
- **Writing**: before writing code in an area below, read its rules and follow their Correct examples
- **Reviewing**: follow "Reviewing Laravel for Rust Code" below
- Related skills: `laravel-rust-testing` (tests), `laravel-rust-audit` (security audit), `laravel-php-to-rust` (porting from Laravel PHP), `rust-for-laravel-developers` (the Rust language)
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Data | CRITICAL | `data-` |
| 2 | Authorization | CRITICAL | `auth-` |
| 3 | Architecture | HIGH | `arch-` |
| 4 | HTTP | HIGH | `http-` |
| 5 | Runtime | HIGH | `run-` |
| 6 | Background Work | HIGH | `jobs-` |
| 7 | Operations | MEDIUM | `ops-` |
## Quick Reference
### 1. Data (CRITICAL)
- `data-eager-load` - `.with(..)` every relationship a list reads; an unloaded one panics into a `500`
- `data-transactions` - Related writes in `db::transaction`; jobs and events wait for the commit, direct mail and HTTP calls do not
- `data-typed-queries-and-raw-sql` - Typed columns; `db::query!` binds variables; map user sort keys to typed orders
- `data-writes-with-fill-structs` - One fill struct per form; `+=` for counters; bulk writes skip events; `tags().delete()` deletes tags
- `data-pagination-order` - Always `order_by` ending in a unique column; cursor pagination for feeds
- `data-relationship-counts` - `with_count` and aggregates instead of loading rows to count them
- `data-chunk-large-sets` - `chunk_by_id` for large tables, never `get()` on all rows
- `data-indexes-and-migrations` - Index what you filter and sort on; `constrained()` is not an index; never edit a migration that ran
- `data-select-only-needed` - `pluck`, `exists`, `first`, and `db::table` projections
### 2. Authorization (CRITICAL)
- `auth-authorize-records` - `authenticated` is not authorization; a policy per record action; `scope_bindings` on nested routes
### 3. Architecture (HIGH)
- `arch-resource-handlers` - The seven actions per module; sub-resources instead of custom verbs; `route!` and `redirect!`
- `arch-config-sections` - `Section` structs, `required` checked at boot; never `std::env::var`
- `arch-container-services` - Singletons hold only shared state; register `T`, not `Arc<T>`; plain functions for domain actions
### 4. HTTP (HIGH)
- `http-input-structs` - `Valid<T>` last; `request.parse` skips validation and authorization
- `http-partial-updates` - `Sometimes<T>` so a PATCH does not clear omitted columns
- `http-errors-with-status` - `#[derive(Status)]` for expected errors; `500` only for failures
- `http-responses-send-only-needed` - Response structs, not whole models, in props and JSON
- `http-middleware-placement` - Middleware that needs the user or session in the `web` group, not global
### 5. Runtime (HIGH)
- `run-concurrent-work` - `task::try_join!` and `task::map` for independent work, not `tokio::spawn`
- `run-blocking-work` - `task::spawn_blocking` for CPU-heavy and synchronous code
- `run-background-vs-queue` - Background tasks are best effort; queue what must happen
- `run-http-client` - `ensure_successful`, timeouts and safe retries
- `run-time-and-clock` - `laravel::now()` so `app.travel` works; UTC stored, converted for display
### 6. Background Work (HIGH)
- `jobs-payloads-retries-idempotency` - Explicit `tries`; idempotent `handle`; stable `name`
- `jobs-thin-schedule` - Named functions or jobs; `without_overlapping` with a shared cache
- `jobs-events-and-listeners` - Queue slow listeners; a listener error fails the dispatch
### 7. Operations (MEDIUM)
- `ops-logging-and-tracing` - Structured fields; `skip_all`; no secrets
- `ops-cargo-features-and-drivers` - Every configured driver has its Cargo feature
- `ops-cache-and-locks` - `remember`; locks with `get`; a shared store across processes
- `ops-deploy-checklist` - Release build, debug off, restart server and workers, graceful shutdown
## Reviewing Laravel for Rust Code
1. **Build and lint**: `cargo build`, `cargo clippy --all-targets`, and `cargo test` where the environment allows. The compiler already rejects input structs without a who-may-submit declaration, extractors in the wrong order, required columns missing from `create!`, and calls into a driver module whose feature is off (but not a configured driver whose feature is off: see `ops-cargo-features-and-drivers`)
2. **Search for these patterns.** A match is a place to read, not a finding
| Search for | What to confirm | Rule |
|---|---|---|
| `#[validate(authenticated)]` or `anyone` on update or delete input; handlers that take a model and write or delete it | A policy check for the record | `auth-authorize-records` |
| Nested routes `/{a}/.../{b}` and nested `resource!` | The child is scoped to the parent (`scope_bindings()`, or a custom key), and the caller is authorized | `auth-authorize-records` |
| Reads of relationship fields (`post.user`, `post.comments`) | The query has `.with(..)`, or the code calls `load` or `load_missing` first; counts need `with_count` | `data-eager-load` |
| `.await` on a query inside a `for` loop | A `with`, `with_count`, `is_in` or single query instead | `data-eager-load`, `data-relationship-counts` |
| `paginate`, `simple_paginate`, `cursor_paginate` | An `order_by` whose columns together are unique | `data-pagination-order` |
| `.get()` or `::all()` in jobs and commands | `chunk_by_id` for large tables | `data-chunk-large-sets` |
| Several writes in one handler, `.send(` of mail, HTTP calls next to writes | `db::transaction`, and what runs before the commit | `data-transactions` |
| `AssertSqlSafe`, `order_by(` with a `String` | Only constants become SQL; sort keys are allow-listed | `data-typed-queries-and-raw-sql` |
| `user_id`, `is_admin` in an input struct; `x: post.x + 1`; `.tags().delete()`; query `update!` or `delete` | Server-side ownership; `+=`; `detach` or `sync`; events not needed | `data-writes-with-fill-structs` |
| `foreign_id(..).constrained()` without an index; new filters or sorts on large tables; edited old migrations | Indexes for the queries; a new migration instead of an edit | `data-indexes-and-migrations` |
| `.get()` followed by `.is_empty()`, `[0]` or a single-field `map` | `exists`, `first`, `pluck` | `data-select-only-needed` |
| `Option<T>` fields (and required `String` fields) in update or PATCH input | `Sometimes<T>`, unless every client always sends every field (a plain HTML form) | `http-partial-updates` |
| `request.parse` on structs with `#[validate]`; Axum `Form`, `Json` or `Query` extractors | `Valid<T>`, `Query<T>` or `request.validate()` | `http-input-structs` |
| `thiserror::Error` types without `Status`; `Error::msg`; `.unwrap()` on input | A status for expected outcomes | `http-errors-with-status` |
| A model, a `Vec` of models or a paginator of models in `props!`, `Json` or shared props (including relationships loaded with `with`) | A response struct | `http-responses-send-only-needed` |
| `middleware.append(..)` in `src/app.rs` for middleware that reads the user or session | The `web` group or route middleware | `http-middleware-placement` |
| `pub async fn` in a handler module that is not one of the seven action names; `Redirect::to(format!(..))`; `resource!(folder::module)` | A sub-resource; `redirect!`; a prefix group | `arch-resource-handlers` |
| `std::env::var` | A `Section` | `arch-config-sections` |
| Fields with `Mutex<Option<..>>` or user data in `#[singleton]` types; `Arc<T>` registered | Shared-only state; `T` registered | `arch-container-services` |
| `tokio::spawn`; sequential awaits of independent queries or calls; loops of API calls | `task::try_join!`, `task::map` (not inside a transaction), `task::spawn` | `run-concurrent-work` |
| `std::thread::sleep`, `std::fs::`, heavy loops in async code | `spawn_blocking` | `run-blocking-work` |
| `task::background`, `dispatch_background`, `send_background`; `QUEUE_CONNECTION` in production | Only best-effort work in the background; a durable queue driver with a worker | `run-background-vs-queue` |
| `client::` calls without `ensure_successful` or `.timeout(`; `.retry(` on a non-idempotent call | Error statuses handled; bounded time; retries only when idempotent | `run-http-client` |
| `SystemTime::now`, `ZonedDateTime::now`; `is_today` on a stored timestamp | `laravel::now()`; the user's timezone for dates | `run-time-and-clock` |
| `#[job]` without `tries`; `handle` with side effects; no `name` | Retries; idempotency (a conditional update or a key); stable name | `jobs-payloads-retries-idempotency` |
| `schedule.call(async ..` closures; `without_overlapping`, `on_one_runner`; the scheduler's cache store | Named functions; `name(..)`; a shared cache store; bounded work | `jobs-thin-schedule` |
| `#[listener]` that sends mail or calls APIs; `events.listen` for a `#[listener]` function | `queued`; registered once | `jobs-events-and-listeners` |
| `tracing::*!("{}", ..)` with secrets; `#[tracing::instrument]` without `skip_all` | Structured fields, no secrets | `ops-logging-and-tracing` |
| Production `CACHE_STORE`, `QUEUE_CONNECTION`, `MAIL_MAILER`, `FILESYSTEM_DISK`, `DB_CONNECTION` | A matching `laravel-rust` Cargo feature for each | `ops-cargo-features-and-drivers` |
| `acquire()` on cache locks; `CACHE_STORE=memory` with several processes | `get`; a shared store | `ops-cache-and-locks` |
| Deploy scripts and process-manager units | Release build, `APP_DEBUG=false`, migrate once, restart server and workers, stop timeouts | `ops-deploy-checklist` |
| `#[job]`, `#[listener]`, `#[singleton]`, `#[schedule::tasks]` in files no `mod` declares | The module is declared, or the item is never registered | `laravel-rust-audit` (`background-declare-modules`) |
3. **Report each finding** with the file and line, what happens (with the status code or the data affected), the rule, and the fix from the rule's Correct example. For a security audit, use `laravel-rust-audit`.
## How to Use the Rules
Read individual rule files for the explanation and examples:
```
rules/data-eager-load.md
rules/auth-authorize-records.md
rules/http-partial-updates.md
```
Each rule file contains:
- Why it matters, with quotes from the docs bundled with `laravel-rust` 0.1.4
- The common version that compiles, and what it does (tested where noted)
- The version to write
## References
- [Laravel for Rust](https://laravel.com/rust)
- [Laravel for Rust documentation](https://laravel.com/rust/docs)
- [laravel/rust skeleton](https://github.com/laravel/rust)
- [laravel-rust on crates.io](https://crates.io/crates/laravel-rust)
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
Files in this skill
- AGENTS.md
- README.md
- SKILL.md
- rules/_sections.md
- rules/_template.md
- rules/arch-config-sections.md
- rules/arch-container-services.md
- rules/arch-resource-handlers.md
- rules/auth-authorize-records.md
- rules/data-chunk-large-sets.md
- rules/data-eager-load.md
- rules/data-indexes-and-migrations.md
- rules/data-pagination-order.md
- rules/data-relationship-counts.md
- rules/data-select-only-needed.md
- rules/data-transactions.md
- rules/data-typed-queries-and-raw-sql.md
- rules/data-writes-with-fill-structs.md
- rules/http-errors-with-status.md
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.