Typed Validation and Forms
Part 2 · Laravel Rust. Accept café orders safely: describe form input as #[laravel::input] structs, add #[validate] rules, require authorization, and block mass-assignment.
Customers are about to place orders on the Rusty Bean Café website. That means data coming from strangers into your database. Some people make typos, some leave fields blank, and a few will try to cheat. In this lesson you’ll learn validation, which checks input before you use it, and see how Laravel Rust turns your form rules into Rust types the compiler can enforce.
Why validate?
Picture the barista reading an order slip. Before making anything, they check: is there a name? Is “quantity: −3” a real amount? Is this person even allowed to order from the staff menu? Only a slip that passes every check goes to the espresso machine.
Validation is that check for your web app. Laravel Rust’s approach:
- You describe the input you expect as a Rust struct.
- You put rules on its fields.
- Your handler only receives the struct once the input passes every rule. If it fails, your handler never runs.
Note
This lesson follows the official Validation guide (opens in new tab), which lists every rule. Laravel Rust is new, so check it if something here looks different in your version.
Your first input struct
First, two routes in src/routes/web.rs: one shows the order form, one receives it.
use laravel::prelude::*;
use crate::http::handlers::orders;
pub fn routes(route: &mut Router) { route.get("/orders/create", orders::create); route.post("/orders", orders::store);}Now describe what the form sends:
use laravel::model::create;use laravel::prelude::*;
use crate::models::{Order, User};
#[laravel::input(fills = Order)]#[validate(authenticated)]pub struct PlaceOrder { #[validate(required, max_length(100))] pub customer_name: String, #[validate(max_length(500))] pub note: Option<String>,}
pub async fn store( Authenticated(user): Authenticated<User>, Valid(input): Valid<PlaceOrder>,) -> laravel::Result<Redirect> { let order = create!(Order { user: &user, ..input }).await?;
Ok(redirect!(show, &order))}PlaceOrder at a glance
| Part | Value |
|---|---|
| Fills | the Order model (fills = Order) |
| Who may submit | #[validate(authenticated)]: any logged-in user |
customer_name: String |
required, max_length(100) |
note: Option<String> |
optional, max_length(500) |
| Handled by | orders::store on POST /orders |
There’s a lot packed in here, so let’s go one piece at a time:
#[laravel::input(...)]marksPlaceOrderas request input. It derives the code that reads form or JSON data into the struct and validates it.fills = Ordermakes it a fill struct for theOrdermodel: each field fills theOrdercolumn with the same name. More on why this matters below.#[validate(authenticated)]says who may submit this form: any logged-in user.#[validate(required, max_length(100))]are rules forcustomer_name: it must be present and not empty, and at most 100 characters. (The launch announcement writes this rule asmax_length = 255, while the official documentation usesmax_length(255); this course follows the documentation.)note: Option<String>is optional. An empty text box arrives asNone, andmax_length(500)only checks it when there’s text.Authenticated(user): Authenticated<User>hands the handler the logged-in user.Valid(input): Valid<PlaceOrder>is the magic. By the time your code runs,inputis guaranteed valid.Valid<T>reads the request body, so it must be the last argument.create!(Order { user: &user, ..input })saves the order.user: &usersetsuser_id, and..inputcopies the form fields, just like Rust’s struct update syntax from Structs.redirect!(show, &order)sends the customer to their new order’s page.
Types do half the work
Notice what you didn’t write. A String field only accepts text, and a number field like u32 only accepts numbers that fit in it. So a quantity field typed u32 already rejects "lots" and -3 with no extra rule.
Rules you’ll use often
Rules go inside #[validate(...)] and run in the order you write them:
| Rule | Passes when the value is |
|---|---|
required |
present and not empty |
min_length(2), max_length(100) |
text of at least / at most that many characters |
min_value(1), max_value(20) |
a number in that range |
one_of("small", "large") |
one of the listed choices |
email |
a valid email address |
confirmed |
the same as the matching _confirmation field |
unique(MenuItem::name) |
not already in that column |
exists(MenuItem::id) |
an id that really exists in that column |
unique and exists take typed columns from your models, so a misspelled column is a compile error, just like in queries.
Here’s a line-item form using several rules at once:
#[laravel::input]#[validate(authenticated)]pub struct AddItem { #[validate(required, exists(MenuItem::id))] pub menu_item_id: i64, #[validate(required, min_value(1), max_value(20))] pub quantity: u32,}Nobody can order 500 croissants, or a menu item that doesn’t exist.
Who may submit? Authorization is required
Every input struct must declare who may submit it, or your code won’t compile. There are three options:
#[validate(anyone)]: anyone who can reach the route, such as a newsletter sign-up.#[validate(authenticated)]: any logged-in user. Guests are sent to the login page (or get a 401 for JSON requests).- A custom
authorizefunction, for anything more specific.
Only staff should add items to the menu. Assuming your users table has an is_admin boolean column, implement ValidatesRequest:
use laravel::prelude::*;use laravel::validation::ValidatesRequest;
use crate::models::{MenuItem, User};
#[laravel::input(fills = MenuItem)]pub struct StoreMenuItem { #[validate(required, max_length(100), unique(MenuItem::name))] pub name: String, #[validate(required, min_value(0))] pub price_cents: i64,}
impl ValidatesRequest for StoreMenuItem { async fn authorize(request: &Request) -> laravel::Result<bool> { let staff = request .user::<User>() .await? .is_some_and(|user| user.is_admin);
Ok(staff) }}authorizeruns before validation.request.user::<User>()gets the logged-in user, if any, as anOption<User>..is_some_and(...)istrueonly when there is a user and they’re an admin.- If it returns
false, the request stops with a 403 “This action is unauthorized.” and the input is never validated.
Important
Because authorization is part of the type, you can’t forget it. A struct without anyone, authenticated or an authorize function is a compile error, not a security hole discovered later.
When validation fails
Your handler never runs with bad input. What the user gets depends on who’s asking:
- A browser form is redirected back to the form. The error messages and the user’s typed input are saved in the session so the form can show them.
- An Inertia page gets the same redirect, with errors in its
errorsprop. - An API client (a request that expects JSON, or a route in
api.rs) gets a 422 Unprocessable Content response with the errors as JSON. For theAddItemform above with the quantity left out, it looks like this:
{ "message": "The quantity field is required.", "errors": { "quantity": ["The quantity field is required."] }}In a server-rendered MiniJinja template (such as resources/views/orders/create.html), old refills what the user typed and error shows a field’s first message:
<input name="customer_name" value="{{ old('customer_name', '') }}">
{% if error('customer_name') %} <p class="error">{{ error('customer_name') }}</p>{% endif %}Mass assignment: why ..input is safe
Here’s a sneaky attack. Your order form shows one text box, customer_name. But anyone can craft their own request and add extra fields:
customer_name=Sam&total_cents=0&status=ready&user_id=1If your code copied every submitted field onto the order, the attacker just got a free, already-prepared order charged to someone else. This bug is called mass assignment: assigning lots of columns at once from untrusted input.
With a fill struct, that can’t happen. PlaceOrder only declares customer_name and note, so ..input only ever fills those two columns. Laravel ignores every field the struct doesn’t declare. user_id comes from Authenticated, and total_cents and status keep their database defaults.
Tip
Make one small fill struct per form, listing only what that form may change. A “rename item” form shouldn’t share a struct with an “edit price” form.
Partial updates with Sometimes<T>
Staff sometimes update just the price of a menu item from a small JSON request:
{ "price_cents": 420 }With a normal field, a missing description would look like “set it to empty”. Sometimes<T> tells the two apart:
use laravel::validation::Sometimes;
#[laravel::input(fills = MenuItem)]pub struct EditMenuItem { #[validate(required, max_length(100))] pub name: Sometimes<String>, #[validate(min_value(0))] pub price_cents: Sometimes<i64>, #[validate(max_length(500))] pub description: Sometimes<Option<String>>,}- A field the request leaves out becomes
Sometimes::Missing, its rules are skipped, and..inputdoesn’t touch that column. - A field the request sends becomes
Sometimes::Present, and its rules run as usual.requirednow means “not empty, if sent”. Sometimes<Option<String>>lets a request clear the description by sendingnull.
The handler then calls update!(menu_item { ..input }).await?, which writes only the fields that arrived. (This handler also needs an authorization, such as the ValidatesRequest impl you wrote for StoreMenuItem.)
Passwords: Password and PasswordHash
Customer accounts need passwords, and passwords need extra care. Laravel Rust gives you two types:
Passwordfor the plain-text password in a form. Its debug output isPassword([redacted]), so it never appears in your logs, and it’s never saved as “old input”.PasswordHashfor the hashed password in the database. It refuses to be turned into JSON, so a hash can’t leak into an API response by accident.
use laravel::hash::Password;
#[laravel::input]#[validate(anyone)]pub struct SignUp { #[validate(required, max_length(255))] name: String, #[validate(required, email, unique(User::email))] email: String, #[validate(required, password, confirmed)] password: Password,}The password rule applies your app’s password requirements (at least 8 characters by default), and confirmed checks a matching password_confirmation field. In the User model, the column is declared as #[serde(skip)] pub password: PasswordHash, and create! hashes a Password for you when you assign it to that column.
Warning
Never store a password as a plain String column. If your database ever leaks, every customer’s password leaks with it. PasswordHash stores a one-way hash instead.
Try it yourself
- Write a
Subscribeinput struct for the café newsletter that anyone may submit, with a required, validemailthat isn’t already in theSubscriber::emailcolumn. - Write a
LeaveReviewfill struct for aReviewmodel with aratingfrom 1 to 5 and an optionalcommentof at most 300 characters. Only logged-in users may submit it.
Show solution
#[laravel::input]#[validate(anyone)]pub struct Subscribe { #[validate(required, email, unique(Subscriber::email))] pub email: String,}
#[laravel::input(fills = Review)]#[validate(authenticated)]pub struct LeaveReview { #[validate(required, min_value(1), max_value(5))] pub rating: u8, #[validate(max_length(300))] pub comment: Option<String>,}Using u8 for the rating means text and negative numbers are rejected by the type itself; the rules handle the 1–5 range.
Recap
- Describe input as a
#[laravel::input]struct with#[validate(...)]rules; take it asValid<T>, the handler’s last argument. - Every input struct must say who may submit it:
anyone,authenticated, or anauthorizefunction. Otherwise it won’t compile. - Failed validation redirects browsers back with errors and old input, and returns 422 JSON to API clients.
fills = Modelplus..inputonly writes the fields you declared, which stops mass assignment.Sometimes<T>separates “not sent” from “sent empty” for partial updates;PasswordandPasswordHashkeep secrets out of logs and JSON.
What’s next
Models and typed queries cover most needs, but sometimes a report is clearest in plain SQL. In Raw Queries with db::query! you’ll write SQL by hand, still safe from injection.
0 of 35 lessons complete