Laravel Rust is the proposal bringing Laravel to Rust, built on the philosophy and structure of Laravel PHP yet tailored to this language. In this introduction, we look at what the project involves, its core features, the installation flow, how to work with AI assistance, and the first steps to build a CRUD.
The guide and reference documentation accompany this early stage while the ecosystem evolves, taking an incremental approach designed to last over time without relying on abrupt changes or early versions subject to adjustments.
The elegance of Laravel, the safety of Rust, and the superpower of AI agents: the new standard for building software at the speed of thought.
A heavy-duty framework for building apps with AI Agents.
Starting Point: Laravel Experience and Working with AI
Starting out with no prior Rust experience is viable when you already know web development and Laravel PHP's architecture, since much of the structure and concepts feel familiar, with the main shift being syntax in .rs files.
With support from AI agents, the developer's focus shifts increasingly toward architecture, technical decisions, and reviewing generated code—letting you move the project forward and learn Rust along the way, while keeping in mind the difference between experimenting or prototyping and maintaining production systems.
This guide assumes you already have Laravel PHP knowledge; for that, you have several resources on the blog and in the academy, specifically on its architecture.
Official page:
Core Features and Performance
At this early stage (in beta), the proposal focuses on the core and key features such as Inertia (configured by default with React when creating a project), queues and workflows, real-time, synchronous execution, validation, agents, and performance, without trying to replicate the entire historical Laravel PHP package ecosystem right away.
Betting on Inertia from the start makes sense for modern applications instead of spinning up a traditional templating engine from scratch. As for performance, Rust delivers higher requests per second (RPS) with lower resource usage compared to interpreted or heavier options—a decisive factor when evaluating efficiency and scalability.
Installing Rust, Cargo, and Laravel CLI
Cargo
To get started, install Rust and its package manager Cargo (equivalent in its package-management role to Composer in PHP or npm in Node) and configure the PATH variable for your environment (Linux, macOS, or Windows).
Ecosystem: Node, Rust, and Git
With the following command we install Rust, Git, and Node; if you already have any of these, do not worry—the installer will not overwrite them:
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shReaders are advised to visit the official page and copy the command from there in case the command changes.
- curl: The command-line tool that downloads the script text file from the internet.
- --proto '=https': Forces the connection to use only the secure HTTPS protocol (preventing redirects to unencrypted HTTP).
- --tlsv1.2: Requires connection encryption to use TLS version 1.2 or higher, ensuring modern security.
- -s (Silent): Hides the progress bar and download stats so it does not clutter the screen.
- -S (Show error): If an error occurs during download, displays the failure message (even in silent mode).
- -f (Fail): Makes curl fail cleanly if the server returns an HTTP error (such as 404 Not Found), preventing an error page from being passed to the interpreter.
- https://sh.rustup.rs: The official web address hosting the script you attached.
If you see output like this:
info: downloading installer
warn: It looks like you have an existing installation of Rust at:
warn: /usr/bin
warn: This could mean one of the following:
warn: - You have already installed rustup: you can quit the installer right now.
warn: - You haven't installed rustup yet, but have Rust installed from elsewhere.
warn: In the latter case, rustup can coexist with and adopt your existing Rust.
warn: To adopt, please reply `yes`, or set RUSTUP_INIT_SKIP_PATH_CHECK to yes,
warn: or pass `-y` to ignore all ignorable checks, then follow the instructions at:
warn: <https://rust-lang.github.io/rustup/installation/already-installed-rust.html>
error: cannot install while Rust is installed
Continue? (y/N) N
error: cannot install while Rust is installed
~ 32sYou already had everything installed and do not need to install it again.
Activate the New Installer's Path in Your Current Terminal
Depending on the shell you use in CachyOS (which is usually Fish by default):
If you use Fish:fish
$ source $HOME/.config/laravel-cli/env.fishIf you use Bash or Zsh:bash
$ source $HOME/.config/laravel-cli/env.shOn macOS:
$ . "$HOME/.cargo/env" Laravel CLI
Unlike the traditional Laravel installer via Composer, here we use the Laravel CLI, a tool designed to create projects across the supported variants (such as Rust, Go, or Laravel PHP), avoiding conflicts with earlier installations if they are no longer used.
We install the Laravel CLI, which now lets you create a project in Rust:
$ curl -fsSL https://laravel.com/install.sh | shYou will see output like:
Changed current directory to /home/andres/.config/composer
./composer.json has been updated
Running composer update laravel/installer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 0 updates, 5 removals
- Removing illuminate/filesystem (v12.72.0)
- Removing laravel/agent-detector (v2.0.5)
- Removing laravel/installer (v5.33.0)
- Removing laravel/prompts (v0.3.27)
- Removing symfony/finder (v7.4.23)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 0 updates, 5 removals
- Removing symfony/finder (v7.4.23)
- Removing laravel/prompts (v0.3.27)
- Removing laravel/installer (v5.33.0)
- Removing laravel/agent-detector (v2.0.5)
- Removing illuminate/filesystem (v12.72.0)
Package tightenco/collect is abandoned, you should avoid using it. Use illuminate/collections instead.
Generating autoload files
23 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.Add it to your PATH:
$ source "$HOME/.config/laravel-cli/env.sh"Laravel CLI Commands
Explore the commands with:
$ laravel -- helpRemove the Laravel Installer
We remove the Laravel installer that we used only with PHP to avoid PATH conflicts:
$ which -a laravel
/Users/andrescruz/.laravel/bin/laravel
/Users/andrescruz/Library/Application Support/Herd/bin//laravelWith:
$ composer global remove laravel/installerYou will get output like:
Changed current directory to /home/andres/.config/composer
./composer.json has been updated
Running composer update laravel/installer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 0 installs, 0 updates, 5 removals
- Removing illuminate/filesystem (v12.72.0)
- Removing laravel/agent-detector (v2.0.5)
- Removing laravel/installer (v5.33.0)
- Removing laravel/prompts (v0.3.27)
- Removing symfony/finder (v7.4.23)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 0 installs, 0 updates, 5 removals
- Removing symfony/finder (v7.4.23)
- Removing laravel/prompts (v0.3.27)
- Removing laravel/installer (v5.33.0)
- Removing laravel/agent-detector (v2.0.5)
- Removing illuminate/filesystem (v12.72.0)
Package tightenco/collect is abandoned, you should avoid using it. Use illuminate/collections instead.
Generating autoload files
23 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
No security vulnerability advisories found.Laravel Rust is not just a language shift—it is a paradigm shift: the productivity we love, armored for the era of AI agents.
Project Creation, Database, and Running the App
With the environment ready, create the project from the terminal specifying the Rust option (for example, via laravel new and selecting Rust or the matching flow). The folder structure shares similarities with Laravel, with directories such as app, resources, routes (like web.rs), and controllers/handlers in Rust (like welcome.rs).
Although the project may initially default to PostgreSQL, you can adapt the database configuration—both in Cargo.toml and in the environment file (.env)—to work with SQLite in development, run migrations, and start the dev server to verify routes, views/components, and behavior on errors like 404.
❯ laravel new testrust
╭
│ ██╗ █████╗ ██████╗ █████╗ ██╗ ██╗ ███████╗ ██╗
│ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██║ ██╔════╝ ██║
│ ██║ ███████║ ██████╔╝ ███████║ ██║ ██║ █████╗ ██║
│ ██║ ██╔══██║ ██╔══██╗ ██╔══██║ ╚██╗ ██╔╝ ██╔══╝ ██║
│ ███████╗ ██║ ██║ ██║ ██║ ██║ ██║ ╚████╔╝ ███████╗ ███████╗
│ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝ ╚══════╝
│
◆ Which language would you like to use? ─────────────────────────╮
│ › ● PHP │
│ ○ Rust │
│ ○ Go │
├───────────────────If you want Rust, you naturally select Rust.
Starting the Server in Development Mode
For that, we have the command:
$ laravel devYou will see the app start compiling:
Blocking waiting for file lock on package cache
[server] Blocking waiting for file lock on package cache
[server] Blocking waiting for file lock on package cache
[server] Compiling libsqlite3-sys v0.40.0
[server] Compiling multer v3.1.0
[server] Compiling sqlx-sqlite v0.9.1
[server] Compiling sqlx v0.9.1
[server] Compiling laravel-rust-core v0.1.4
[server] Compiling laravel-rust-redis v0.1.4
[server] Compiling laravel-rust-client v0.1.4
[server] Compiling laravel-rust-database v0.1.4
[server] Compiling laravel-rust-console v0.1.4
[server] Compiling laravel-rust-cache v0.1.4
[server] Compiling laravel-rust-http v0.1.4And processes like Vite spin up while more info shows up:
[vite] ➜ APP_URL: http://localhost:8000
[server] Blocking waiting for file lock on build directory
[server] Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.55s
[server] Running `target/debug/testrust`
[queue] Processing jobs from `database:default`. Press Ctrl+C to stop.
[server] failed to serve on `127.0.0.1:8000`: Address already in use (os error 98)
[vite] Inertia SSR dev endpoint: /__inertia_ssr
[vite] WarminYou might hit some errors if you do not have PSQL configured, which is the default—so let us switch it.
Switching from PSQL to SQLite
Dependencies
We add the SQLite dependency ("database-sqlite") in Cargo.toml, which is the equivalent of composer.json in the dependencies section:
Cargo.toml
[dependencies]
laravel-rust = { version = "0.1", features = ["database-postgres", "database-sqlite", "redis", "sqs"] }By default, it uses PSQL, but we can switch to SQLite:
.env
# # DB_CONNECTION=postgres
# # DATABASE_URL=postgres://postgres@127.0.0.1/laravel
DB_CONNECTION=sqlite
DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwcRun:
$ laravel migrateAnd you will get output:
◇ Migrating `0001_01_01_000000_create_users_table`...
◇ Migrating `0001_01_01_000001_create_cache_table`...
◇ Migrating `0001_01_01_000002_create_jobs_table`...
◆ 3 migrations ran.And now you will see the project running at:
Workflow, Commits, and Preparing the CRUD
When working with AI and incremental review, it helps to move in small steps and record each milestone or feature in clear commits inside the repository—making it easier to compare changes, audit generated code, and see how routes, handlers, models/factories, and views connect.
With the foundation up and running and the official documentation as a reference for topics like routing, middleware, requests, pagination, and databases, the natural next step is building the first full CRUD to solidify the workflow in Laravel Rust.
First CRUD and Authentication in Laravel Rust with AI Agents
Building the first CRUD and authentication in Laravel Rust with an AI agent—such as OpenCode with a free model or a capable local model—lets you move forward without getting bogged down in every initial Rust syntax detail.
The approach starts from understanding Laravel's foundations and architecture so you absorb the language progressively, keeping a practical, focused guide as the framework evolves.
1. Project Skills and the Developer's Role
Inspecting the project and its associated files or skills shows that these guides or instructions support using the agent, but are not part of the final application code.
Areas covered include writing Rust code and routes/handlers, databases, migrations, models and relationships, factories, input validation, authentication and authorization, queues and jobs, testing, and Inertia.
The developer's job is to guide design and architecture with their own judgment, delegating repetitive execution to the agent and reviewing the result.
2. Models and Migrations
Starting from a simple entity—such as categories with a title and slug, and posts linked via a relationship—you can generate the corresponding models and migrations.
In this structure, the entity definition brings together typed fields (such as i64 integers or strings) and relationships in a single file, in a more compact, less fragmented style than some traditional structures.
In the terminal, CLI commands and project utilities are used to inspect routes or run migrations, keeping asynchronous operations (await) in mind when interacting with the database from handlers.
Crea un modelo de Post con title,slug description, posted y category_id (Category es otro modelo que debes de crear title y slugAnd we get output like:
Listo. Creé los dos modelos con sus migraciones ya ejecutadas en la BD local (storage/app/database.sqlite).
Modelos
src/models/post.rs
#[model]
pub struct Post {
pub id: i64,
pub category_id: i64,
pub title: String,
pub slug: String,
pub description: String,
#[default]
pub posted: bool,
pub created_at: Timestamp,
pub updated_at: Timestamp,
#[belongs_to]
pub category: BelongsTo<Category>,
}
src/models/category.rs — id, title, slug, timestamps y #[has_many] posts: HasMany<Post>.
Ambos con factory en el mismo archivo (convención del proyecto) y re-exportados desde src/models/mod.rs.
Migraciones
- database/migrations/2026_12_02_000000_create_categories_table.rs — slug único.
- database/migrations/2026_12_02_000001_create_posts_table.rs — slug único, description como text, category_id con FK a categories y cascade_on_delete, índice en category_id.
Decisiones a confirmar
- posted lo interpreté como booleano (por eso posted y no posted_at), con default(false) en la BD y #[default] en el modelo para poder omitirlo en create!. Si querías una fecha de publicación, lo cambio a posted_at: Option<Timestamp>.
- Category::posts() y Post::category no se cargan automáticamente en laravel-rust: hay que usar .with(...) o consultarlos explícitamente.
Verificación
- cargo check --all-targets y cargo clippy --all-targets limpios.
- Añadí tests/posts.rs con un test real: crea una categoría, un post con for_(Post::category, &category), comprueba category_id, el default posted = false y la relación inversa. Pasa.
- laravel migrate aplicó las 2 migraciones.
No creé handlers ni páginas Inertia porque no los pediste; dime si quieres el CRUD.And the models with their factories:
src/models/post.rs
use laravel::model::{BelongsTo, Faker, IntoCreate, create, factory, model};
use laravel::time::Timestamp;
use crate::models::Category;
#[model]
pub struct Post {
pub id: i64,
pub category_id: i64,
pub title: String,
pub slug: String,
pub description: String,
#[default]
pub posted: bool,
pub created_at: Timestamp,
pub updated_at: Timestamp,
#[belongs_to]
pub category: BelongsTo<Category>,
}
#[factory(Post)]
pub struct PostFactory;
impl PostFactory {
fn definition(fake: &mut Faker) -> impl IntoCreate<Post> {
create!(Post {
category: Category::factory(),
title: fake.sentence(),
slug: fake.unique().slug(),
description: fake.paragraph(),
})
}
}src/models/category.rs
use laravel::model::{Faker, HasMany, IntoCreate, create, factory, model};
use laravel::time::Timestamp;
use crate::models::Post;
#[model]
pub struct Category {
pub id: i64,
pub title: String,
pub slug: String,
pub created_at: Timestamp,
pub updated_at: Timestamp,
#[has_many]
pub posts: HasMany<Post>,
}
#[factory(Category)]
pub struct CategoryFactory;
impl CategoryFactory {
fn definition(fake: &mut Faker) -> impl IntoCreate<Category> {
create!(Category {
title: fake.sentence(),
slug: fake.unique().slug(),
})
}
}Migrations
Crea las migraciones de ambos modelosResponse:
Ya están creadas y aplicadas desde el paso anterior — no falta nada por generar. Están en:
database/migrations/2026_12_02_000000_create_categories_table.rs
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("categories", |table| {
table.id();
table.string("title");
table.string("slug").unique();
table.timestamps();
})
.await
}
database/migrations/2026_12_02_000001_create_posts_table.rs
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("posts", |table| {
table.id();
table.foreign_id("category_id").constrained().cascade_on_delete();
table.string("title");
table.string("slug").unique();
table.text("description");
table.boolean("posted").default(false);
table.timestamps();
table.index(["category_id"]);
})
.await
}
La tabla migrations confirma que ambas corrieron, y el esquema real en SQLite ya tiene categories y posts.
Si lo que quieres es otra cosa, dime cuál:
- Regenerarlas con el generador (laravel make:migration ...) para que los nombres lleven la marca UTC actual — ojo, eso duplicaría tablas si se ejecutan, habría que borrar primero las que ya corren.
- Cambiar el esquema: por ejemplo description nullable, posted como posted_at, o slug sin índice único.
- Rehacer la BD desde cero con laravel migrate:fresh una vez ajustado el esquema.If you inspect the database you will see the tables created.
By hand it would be:
$ laravel make:migrationAnd then:
$ laravel migrate 3. CRUD, Routes, Handlers, and Views with Inertia
With the model and migration ready, you implement the full categories CRUD (listing, creation, editing, deletion, and associated routes) along with server-side validation and frontend pages with Inertia (for example, with React).
In handlers, requests, validations, queries (taking care to avoid N+1 query issues), and responses are managed, returning results and controlled redirects using types like Ok or Inertia responses.
In the UI, starting from simple initial templates or views, it is worth building reusable components (such as inputs, labels, buttons, and tables) and using Inertia's own navigation to preserve single-page application (SPA) behavior.
Crea el controlador CRUD para las categorias y los componentes de React con validaciones en servidor y sus rutasThe output:
CRUD completo de categorías funcionando: handlers, validación en servidor, rutas, páginas Inertia y tests.
Backend
src/http/handlers/categories.rs — las 7 acciones estándar:
Rutas (resource!(categories) en src/routes/web.rs) Handler
GET /categories index (ordenado por título)
GET /categories/create create
POST /categories store
GET /categories/{category} show
GET /categories/{category}/edit edit
PUT/PATCH /categories/{category} update
DELETE /categories/{category} destroy
Validación con structs tipados (Valid<T>), no a mano:
#[laravel::input(fills = Category)]
#[validate(anyone)]
pub struct StoreCategory {
#[validate(required, max_length(255))]
pub title: String,
#[transform(lowercase)]
#[validate(required, max_length(255), alpha_dash, unique(Category::slug))]
pub slug: String,
}
UpdateCategory usa unique(Category::slug, ignore = route("category")), así que guardar sin cambiar el slug no falla por "ya existe".
- #[transform(lowercase)] normaliza el slug antes de validar y guardar (Hardware → hardware); alpha_dash rechaza espacios y símbolos.
- fills = Category garantiza que solo se escriban title y slug.
- inertia::flash("success", ...) y redirect! a show tras crear/editar, a index tras borrar.
Frontend (resources/js/)
- layouts/AppLayout.tsx — cabecera con navegación y banner del flash.
- components/CategoryForm.tsx — formulario compartido con useForm (necesario para enviar el PUT), errores por campo y estado processing.
- components/DeleteCategoryButton.tsx — borrado con confirmación vía router.delete.
- pages/Categories/{Index,Create,Edit,Show}.tsx — listado, alta, edición y detalle.
- types/index.ts — tipo Category compartido.
Los errores de validación llegan a errors.title / errors.slug y se muestran bajo cada input sin perder lo escrito.
Tests (tests/categories.rs, 8 tests)
Listado ordenado, render del formulario, alta (incluye el lowercase del slug), título requerido, slug único, slug con espacios/símbolos, actualización y borrado. Todos verifican respuesta Inertia, flash y estado real en base de datos.
Verificado
- cargo test → 8 nuevos + los existentes en verde.
- cargo clippy --all-targets limpio.
- npm run types:check, npm run check y npm run build sin errores.
- laravel route:list muestra las 7 rutas.
Dos decisiones que puedes querer cambiar: el CRUD es público (#[validate(anyone)]) porque el proyecto aún no tiene login; si añades auth, se cambia a #[validate(authenticated)] y se protege el grupo con Authenticate. Y el index carga todas las categorías sin paginar; cuando crezcan, conviene paginar con order_by(Category::title).paginate(...).src/http/handlers/categories.rs
use laravel::inertia::{self, Page, props};
use laravel::model::{create, update};
use laravel::prelude::*;
use crate::models::Category;
#[laravel::input(fills = Category)]
#[validate(anyone)]
pub struct StoreCategory {
#[validate(required, max_length(255))]
pub title: String,
#[transform(lowercase)]
#[validate(required, max_length(255), alpha_dash, unique(Category::slug))]
pub slug: String,
}
#[laravel::input(fills = Category)]
#[validate(anyone)]
pub struct UpdateCategory {
#[validate(required, max_length(255))]
pub title: String,
#[transform(lowercase)]
#[validate(required, max_length(255), alpha_dash, unique(Category::slug, ignore = route("category")))]
pub slug: String,
}
// #[laravel::auth::page(home)]
pub async fn index() -> laravel::Result<Page> {
let categories = Category::query().order_by(Category::title.asc()).get().await?;
Ok(inertia::render("Categories/Index", props! { categories }))
}
pub async fn create() -> Page {
inertia::render("Categories/Create", props! {})
}
pub async fn store(Valid(form): Valid<StoreCategory>) -> laravel::Result<Redirect> {
let category = create!(Category { ..form }).await?;
inertia::flash("success", "Category created.")?;
Ok(redirect!(show, &category))
}
pub async fn show(category: Category) -> Page {
inertia::render("Categories/Show", props! { category })
}
pub async fn edit(category: Category) -> Page {
inertia::render("Categories/Edit", props! { category })
}
pub async fn update(mut category: Category, Valid(form): Valid<UpdateCategory>) -> laravel::Result<Redirect> {
update!(category { ..form }).await?;
inertia::flash("success", "Category updated.")?;
Ok(redirect!(show, &category))
}
pub async fn destroy(category: Category) -> laravel::Result<Redirect> {
category.delete().await?;
inertia::flash("success", "Category deleted.")?;
Ok(redirect!(index))
}4. CLI Commands
With the Laravel CLI, we have commands we can use:
$ laravel route:listWe will see our category routes:
❯ laravel route:list
Method URI Handler
GET|HEAD / welcome::show
GET|HEAD /categories categories::index
GET|HEAD /categories/create categories::create
POST /categories categories::store
GET|HEAD /categories/{category} categories::show
GET|HEAD /categories/{category}/edit categories::edit
PUT|PATCH /categories/{category} categories::update
DELETE /categories/{category} categories::destroy
GET|HEAD /api/version Closure
POST /broadcasting/auth laravel::channels::Channels
GET|POST|HEAD /_workflow/resume laravel::url::accept
ANY /{fallback} ClosureAnd the help command:
$ laravel helpWhich are the same commands we use in the Laravel installer with Composer.
Other Changes
From here on, you can make other changes such as creating form components since, unlike Laravel with PHP—at least for now—we do not have anything to reuse yet, so we create a few:
Vamos a crear los componentes, textarea, input, label y buttons con variantes de success primary y danger y tablaAnd it generated a folder with several components:
And it generated a folder with several components:
- resources/js/components/ui
- resources/js/components/ui/Button.tsx
- resources/js/components/ui/Checkbox.tsx
- resources/js/components/ui/Field.tsx
- resources/js/components/ui/index.ts
- resources/js/components/ui/Input.tsx
- resources/js/components/ui/Label.tsx
- resources/js/components/ui/Select.tsx
- resources/js/components/ui/Textarea.tsx
Next, the CRUD for posts:
Ahora el CRUD para los postAnd so on, building more and more components; in the repository linked to this content, you can browse the commits to see the output generated for each instruction given to the AI:
https://github.com/libredesarrollo/course-book-laravel-rust/commits/main/
4. Authentication and Next Steps
In the project's current state, the core provides base authentication support and an authenticatable user, while the visual scaffolding (login, registration, and logout pages) and route or middleware wiring (such as protecting routes or redirecting authenticated users) are completed inside the application.
It is also worth adding request rate controls (rate limiting) on entry endpoints to prevent abuse or overload.
Once the base CRUD and authentication are validated, the natural flow is to extend the system with permissions, more complex relationships, and richer UI components, integrating this path into the ecosystem's broader learning roadmap.
Para el login, que tenemos, ya que veo que NO provee nada por defecto, que opciones tenemosWe get:
Antes de elegir, un matiz importante: el framework sí trae la autenticación, lo que no trae es el scaffolding (rutas, formularios y páginas). Es la diferencia entre "Breeze" y "las piezas de auth".
Lo que ya existe en el proyecto (lo verifiqué en el código y los docs instalados)
- Guard de sesión ya registrado en src/app.rs: auth.session::<model::Users<User>>().
- User deriva Authenticatable y la tabla users ya tiene password y remember_token.
- Authenticate (protege rutas) y RedirectIfAuthenticated (solo invitados).
- Auth<User> con attempt, validate, login, logout; regeneración de sesión, bcrypt, "remember me" de 400 días.
- Helpers de rate limit para el login y tipo Password que evita que la contraseña acabe en logs.
- Extras ya documentados: Passwords<User> (reset), MustVerifyEmail, y módulo social (Google/GitHub/Microsoft).
- Testing: acting_as($user), fakes y aserciones.As interesting highlights, we already have the backend in Laravel—what is missing is the frontend—so you can see how it works in route middleware such as:
src/routes/web.rs
route.middleware(Authenticate).group(|route| {
route.post("/logout", auth::logout);
resource!(categories);
resource!(posts);
});Which protect those routes and associated files you can inspect in the repository.
PHP vs Rust
1 async fn and .await
In PHP, a request is synchronous: you call the database and the thread waits. In Rust, the handler is declared async and operations that wait (database, disk, network) return a future: a promise of a future value.
public function index()
{
$categories = Category::orderBy('title')->get();
return Inertia::render('Categories/Index', [
'categories' => $categories,
]);
}pub async fn index() -> laravel::Result<Page> {
let categories = Category::query()
.order_by(Category::title.asc())
.get()
.await?;
Ok(inertia::render("Categories/Index", props! { categories }))
}The Three Practical Rules
- A future does nothing until you await it. In PHP
->get()already runs the query; in Rust.get()only builds the operation. You need.await. .await?= await and, if it failed, bail out. First it waits (await) and then it propagates the error (?). It is the equivalent of letting an exception bubble up on its own, written inline.- If the function is
async, whoever calls it is too. That is why all handlers arepub async fn: the framework awaits them for you.
.await does not cause a logic error—it causes a type error: categories would be a future rather than a list of categories. The compiler warns you before running the app.2 The Role of Ok and Result
In PHP, success is simply return $value; errors are thrown with throw and caught by the framework. In Rust, the possibility of failure is encoded in the return type:
pub async fn index() -> laravel::Result<Page>This reads: "I return a Page or an error". laravel::Result<T> is an alias for Result<T, laravel::Error>. And a Result can only be constructed in two ways:
Ok(value)— everything went well; here is the value.Err(error)— something failed. Normally you do not write it yourself:?produces it.
That is why the handler ends with Ok(...): it is not a function that "prints" something—it is how you wrap the success value so the types match.
The ? Operator
Each ? means: "if this is an Err, return it as the handler's error right now." It is an implicit throw, yet visible and type-checked.
pub async fn store(Valid(form): Valid<StoreCategory>) -> laravel::Result<Redirect> {
let category = create!(Category { ..form }).await?; // if the INSERT fails, stop here
inertia::flash("success", "Category created.")?; // if flash fails, stop here
Ok(redirect!(show, &category)) // success
}When Is There NO Result?
When the function cannot fail. That is why create() and show() return plain Page:
// No database or anything that can fail: no Result needed.
pub async fn create() -> Page {
inertia::render("Categories/Create", props! {})
}
// show receives the already-resolved category; it cannot fail either.
pub async fn show(category: Category) -> Page {
inertia::render("Categories/Show", props! { category })
}-> laravel::Result<T> when there is a ? inside; -> T when it always returns a value.3 How Values Are Returned at the End
Rust returns the last expression in the block, with no return and no semicolon. A ; turns the expression into a statement and discards its value.
return Inertia::render('Categories/Show', [
'category' => $category,
]);inertia::render("Categories/Show", props! { category })
// no `return`, no trailing `;`return does exist in Rust, but it is used to exit early (early return). In these handlers you will rarely see it: if something fails, ? handles it.
pub async fn destroy(category: Category) -> laravel::Result<Redirect> {
category.delete().await?;
inertia::flash("success", "Category deleted.")?;
Ok(redirect!(index)) ← this is the normal exit
}So in a function returning Result, you have two exits:
- error exit: produced by any
?that encounters anErr; - normal exit: the final expression, here
Ok(redirect!(index)).
Ok(redirect!(index));. That ; makes the function return (), and the compiler will say it expected Result<Redirect> and found ().4 Validation in the Same File
In PHP, you normally use a separate FormRequest or $request->validate([...]) inside the method. In Laravel for Rust, validation is an attributed struct declared in the same file as the handler.
public function store(Request $request)
{
$validated = $request->validate([
'title' => ['required', 'max:255'],
'slug' => [
'required', 'max:255', 'alpha_dash',
Rule::unique('categories', 'slug'),
],
]);
$category = Category::create($validated);
return redirect()->route('categories.show', $category);
}#[laravel::input(fills = Category)]
#[validate(anyone)]
pub struct StoreCategory {
#[validate(required, max_length(255))]
pub title: String,
#[transform(lowercase)]
#[validate(required, max_length(255), alpha_dash, unique(Category::slug))]
pub slug: String,
}
pub async fn store(Valid(form): Valid<StoreCategory>)
-> laravel::Result<Redirect>
{
let category = create!(Category { ..form }).await?;
Ok(redirect!(show, &category))
}What the Struct Gains You
- Column names are checked at compile time. A typo like
unique(Category::sulg)never makes it to runtime. - Types validate out of the box. You do not need a
stringrule: the field is already aString. A number will not fit into aString. fills = Categoryacts as an allowlist. Only fields declared on the struct get written; if someone sendsis_admin=1, it is ignored. This replaces$fillable/$request->validated().#[transform(lowercase)]normalizes before validating and saving, so"Hardware"passes the rule and is saved as"hardware".ignore = route("category")is the equivalent of->ignore($category): when editing, the current row does not count as a duplicate.
Who Can Submit the Form
#[validate(anyone)] does not validate data—it authorizes. It is the spot where in PHP you would put middleware('auth') or a Gate. With login enabled, you would switch it to #[validate(authenticated)].
How the Form Reaches the Handler
Valid(form): Valid<StoreCategory> is an argument that does three things at once: reads the body, validates it, and converts it into the struct. If validation fails, the handler does not run: Laravel redirects back with errors (or responds with 422 in JSON). The handler only ever sees valid data.
Valid<T> consumes the request body, so it must be the last argument in the handler.5 Handler Arguments: Injection and Automatic 404
This part feels very close to PHP: the framework resolves arguments for you.
public function show(Category $category)
{
return Inertia::render('Categories/Show', [
'category' => $category,
]);
}pub async fn show(category: Category) -> Page {
inertia::render("Categories/Show", props! { category })
}{category}in the URL is looked up in the table and, if missing, returns 404 automatically—just like route model binding in PHP.- An argument can be a validation struct, a model, the authenticated user, or a service from the container.
- There is no magic
$request: you ask only for what you need.
6 Macros: create!, update!, redirect!, props!
Macros end with !. They are not regular functions: they generate code at compile time. That is what allows column names and route names to be checked before startup.
| PHP | Rust | What the Compiler Checks |
|---|---|---|
Category::create($data) | create!(Category { ..form }).await? | that columns exist and types match |
$category->update($data) | update!(category { ..form }).await? | the same; also requires mut category |
redirect()->route('categories.show', $c) | redirect!(show, &category) | that the show handler exists and has a route |
['category' => $category] | props! { category } | nothing special; syntax sugar to avoid repeating the key |
In redirect!(show, &category), the & means "borrow" the category instead of giving it away; the model remains available afterward for other operations. In PHP, objects are passed by reference without thinking about it; in Rust, you have to state it explicitly.
7 Equivalence Table
| Concept | Laravel PHP | Laravel for Rust |
|---|---|---|
| Action | public function index() | pub async fn index() |
| Success | return $x; | Ok(x) as the final expression |
| Failure | throw / exception | Err in the return type + ? |
| Await I/O | implicit | explicit .await |
| Validate | $request->validate([...]) | struct with #[validate(...)] |
| Field allowlist | $fillable | fills = Model |
| Unique rule on edit | unique(...)->ignore($id) | unique(Post::slug, ignore = route("post")) |
| Response | Inertia::render('X', [...]) | inertia::render("X", props! { .. }) |
| Redirect | redirect()->route('x.show', $m) | redirect!(show, &m) |
| Binding 404 | automatic | automatic |
| CRUD routes | Route::resource('categories', ...) | resource!(categories); |
8 Common Beginner Mistakes
- Forgetting
.await. The variable stays as a future instead of a list or model. If the compiler says "unused future" or the type does not match what you expected, an.awaitis missing. - Forgetting
Ok(...). If the signature returnsResult<Page>, ending with plainPagewill not compile: you have to wrap it. - Putting
;on the final expression. It turns the value into()and breaks the return type. - Forgetting
mutwhen updating.update!(category { ..form })mutates the model in memory; the variable must bemut category: Category. - Not importing the prelude.
use laravel::prelude::*;brings inValid,Redirect,redirect!,route!, andor_abort. Without it, the documentation examples will not compile. - Using
$orreturnout of habit. In Rust there is no$: useletvariables, types after:, and?instead of exceptions.