28 / 35

Data, Models & Forms· 14 min read· Lesson 28 of 35

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:

  1. You describe the input you expect as a Rust struct.
  2. You put rules on its fields.
  3. 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.

src/routes/web.rs
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:

src/http/handlers/orders.rs
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:

  1. #[laravel::input(...)] marks PlaceOrder as request input. It derives the code that reads form or JSON data into the struct and validates it.
  2. fills = Order makes it a fill struct for the Order model: each field fills the Order column with the same name. More on why this matters below.
  3. #[validate(authenticated)] says who may submit this form: any logged-in user.
  4. #[validate(required, max_length(100))] are rules for customer_name: it must be present and not empty, and at most 100 characters. (The launch announcement writes this rule as max_length = 255, while the official documentation uses max_length(255); this course follows the documentation.)
  5. note: Option<String> is optional. An empty text box arrives as None, and max_length(500) only checks it when there’s text.
  6. Authenticated(user): Authenticated<User> hands the handler the logged-in user.
  7. Valid(input): Valid<PlaceOrder> is the magic. By the time your code runs, input is guaranteed valid. Valid<T> reads the request body, so it must be the last argument.
  8. create!(Order { user: &user, ..input }) saves the order. user: &user sets user_id, and ..input copies the form fields, just like Rust’s struct update syntax from Structs.
  9. 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 authorize function, for anything more specific.

Only staff should add items to the menu. Assuming your users table has an is_admin boolean column, implement ValidatesRequest:

src/http/handlers/menu.rs
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)
}
}
  1. authorize runs before validation.
  2. request.user::<User>() gets the logged-in user, if any, as an Option<User>.
  3. .is_some_and(...) is true only when there is a user and they’re an admin.
  4. 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 errors prop.
  • 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 the AddItem form above with the quantity left out, it looks like this:
Output
{
"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:

Output
<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:

Output
customer_name=Sam&total_cents=0&status=ready&user_id=1

If 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:

Output
{ "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>>,
}
  1. A field the request leaves out becomes Sometimes::Missing, its rules are skipped, and ..input doesn’t touch that column.
  2. A field the request sends becomes Sometimes::Present, and its rules run as usual. required now means “not empty, if sent”.
  3. Sometimes<Option<String>> lets a request clear the description by sending null.

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:

  • Password for the plain-text password in a form. Its debug output is Password([redacted]), so it never appears in your logs, and it’s never saved as “old input”.
  • PasswordHash for 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

  1. Write a Subscribe input struct for the café newsletter that anyone may submit, with a required, valid email that isn’t already in the Subscriber::email column.
  2. Write a LeaveReview fill struct for a Review model with a rating from 1 to 5 and an optional comment of 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 as Valid<T>, the handler’s last argument.
  • Every input struct must say who may submit it: anyone, authenticated, or an authorize function. Otherwise it won’t compile.
  • Failed validation redirects browsers back with errors and old input, and returns 422 JSON to API clients.
  • fills = Model plus ..input only writes the fields you declared, which stops mass assignment.
  • Sometimes<T> separates “not sent” from “sent empty” for partial updates; Password and PasswordHash keep 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

Search lessons

Type to search all lessons.