← All guides

Published · 5 min read

Validation and form requests in Laravel Rust

From FormRequest classes to typed input structs: rules, authorization, transforms, partial updates and checks against the database, shown on an airline refund form.

  • validation
  • forms
  • handlers
On this page
  1. The form request you’d write today
  2. The same form in Laravel Rust
  3. The handler
  4. When validation fails
  5. Checks that rules can’t express
  6. Authorization that needs a record
  7. PATCH requests and Inertia partial forms
  8. Rule names you already know

In Laravel PHP, a form request is a class with two methods: authorize() and rules(). Laravel Rust keeps both ideas, but moves the rules onto a struct that describes the input. The struct’s field types do half the validation for you, and the compiler makes sure you never forget the authorization half.

The form in this guide is an airline’s refund request. A signed-in passenger enters a booking reference, their email, the flight date and a reason, plus optional details.

The form request you’d write today

// app/Http/Requests/StoreRefundRequest.php
class StoreRefundRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'booking_reference' => strtoupper((string) $this->booking_reference),
            'email' => strtolower((string) $this->email),
        ]);
    }

    public function rules(): array
    {
        return [
            'booking_reference' => ['required', 'regex:/^[A-Z0-9]{6}$/', 'exists:bookings,reference', 'unique:refund_requests'],
            'email' => ['required', 'email'],
            'reason' => ['required', Rule::enum(RefundReason::class)],
            'flight_date' => ['required', 'date', 'before_or_equal:today'],
            'details' => ['nullable', 'string', 'max:1000'],
        ];
    }
}

The same form in Laravel Rust

// src/http/handlers/refunds.rs
use laravel::prelude::*;
use laravel::time::civil::Date;

use crate::models::{Booking, RefundRequest};

#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum RefundReason {
    Cancelled,
    Delayed,
    DuplicateCharge,
}

#[laravel::input(fills = RefundRequest)]
#[validate(authenticated)]
pub struct StoreRefund {
    #[transform(uppercase)]
    #[validate(bail, required, regex(r"\A[A-Z0-9]{6}\z"), exists(Booking::reference), unique(RefundRequest::booking_reference))]
    booking_reference: String,
    #[transform(lowercase)]
    #[validate(required, email)]
    email: String,
    reason: RefundReason,
    #[validate(required, today_or_before)]
    flight_date: Date,
    #[validate(max_length(1000))]
    details: Option<String>,
}

Each part of the form request has a place in the struct:

#[validate(authenticated)] is authorize(). Every input struct a handler validates must say who may submit it: anyone, authenticated, a policy, or your own authorize function. Leave it out and the code doesn’t compile. A guest gets what the Authenticate middleware would give them: a redirect to login, or a 401 for JSON.

#[transform(...)] is prepareForValidation(). The uppercase and lowercase transforms run as soon as the request is decoded, before any rule sees the value. So exists and unique query the database with AB12CD, even if the passenger typed ab12cd. If the form fails, the old input still shows what they actually typed.

The types replace a third of the rules. reason is an enum, so only cancelled, delayed and duplicate_charge are accepted: no Rule::enum needed. flight_date is a Date, so it must be a real date. details is an Option, which is how you say nullable.

bail works per field, as before. If the reference doesn’t match the pattern, the two database rules never run.

What happens to a form submission before the handler runs: authorize, then decode into the struct with transforms applied, then the rules. A guest is sent to log in. A wrong type or a failed rule sends browsers back with errors and old input, and JSON clients get a 422.

The handler

use laravel::model::create;

pub async fn store(Valid(form): Valid<StoreRefund>) -> laravel::Result<Redirect> {
    let refund = create!(RefundRequest { ..form }).await?;

    Ok(redirect!(show, refund.id))
}

Valid<StoreRefund> is the type-hinted StoreRefundRequest $request of Laravel PHP. The handler only runs once authorization and every rule have passed. It has to be the last argument, because it reads the request body.

fills = RefundRequest turns the struct into a fill struct for the model, and ..form copies its fields into the new row. It’s also your mass-assignment protection: a request can only write the columns the struct declares. Sending status=approved alongside the form does nothing, because there’s no status field to receive it.

Tip: need the request too? Valid<T> and Request both read the body, so a handler can’t take both. Take ValidRequest<StoreRefund> instead, and call into_parts() to get the input and the request back.

When validation fails

Nothing changes for your users:

  • A browser form on a web route is redirected back, with the errors and old input in the session.
  • An Inertia form gets the same redirect, and the errors arrive in the page’s errors prop.
  • A JSON request, or any api route, gets a 422 with a message and an errors object keyed by field.

Checks that rules can’t express

One refund rule needs two fields at once: the date the passenger entered must be the date of their booked flight. A single-field rule can’t see that, so do it in the handler and report it with invalid!:

use laravel::validation::invalid;

pub async fn store(Valid(form): Valid<StoreRefund>) -> laravel::Result<Redirect> {
    let booking = Booking::query()
        .filter(Booking::reference.eq(&form.booking_reference))
        .first_or_fail()
        .await?;

    if booking.flight_date != form.flight_date {
        invalid!(flight_date => "That isn't the date of the flight on this booking.");
    }

    let refund = create!(RefundRequest { ..form }).await?;

    Ok(redirect!(show, refund.id))
}

The passenger sees this exactly like a failed rule: redirected back with the message under the date field, or a 422 for an API client. In PHP you’d reach for withValidator() or after() for this; here it’s ordinary code after validation.

For several problems at once, collect them in an InvalidInput with errors.add(field, message) and return it.

Authorization that needs a record

authenticated covers “any signed-in user”. When the answer depends on a record in the URL, name a policy method and the route parameter:

#[laravel::input]
#[validate(authorize(RefundPolicy::update, route("refund")))]
pub struct UpdateRefund {
    #[validate(max_length(1000))]
    details: Option<String>,
}

On PUT /refunds/{refund}, Laravel loads the refund and asks RefundPolicy::update whether the current user may change it. A denial gets the policy’s response, such as a 403.

When the decision or the rules depend on the request in more complex ways, implement ValidatesRequest on the struct. Its authorize function is required, and its optional rules function adds rules to the ones on the fields. Inside rules, request.model("refund") finds the record from the URL once, and your handler can take the same model as an argument without a second query.

PATCH requests and Inertia partial forms

A JSON PATCH usually sends only the fields that changed. With plain fields you can’t tell “left out” from “sent empty”. Sometimes<T> can:

use laravel::validation::Sometimes;

#[laravel::input]
#[validate(authenticated)]
pub struct UpdateContactPreferences {
    #[validate(required, email)]
    email: Sometimes<String>,
    #[validate(max_length(20))]
    phone: Sometimes<Option<String>>,
}

A field the request leaves out is Sometimes::Missing, and none of its rules run, not even required. A field it sends is Sometimes::Present, and its rules run normally. Here, required means “not empty, if sent”, and sending phone: null clears the number. When you save a fill struct, Missing fields are skipped, so those columns keep their values. In Laravel PHP you’d write sometimes in the rules; here it’s in the type.

Rule names you already know

Most rules have the names you’d expect, written as Rust calls:

Laravel PHP Laravel Rust
'max:255' on a string max_length(255)
'min:1' on a number min_value(1)
'in:draft,published' one_of("draft", "published")
'exists:bookings,reference' exists(Booking::reference)
'unique:users,email' unique(User::email)
'after:starts_on' after(starts_on)
'required_if:delivery,ship' required_if(delivery, "ship")
'nullable' An Option field
'sometimes' A Sometimes field

Because exists and unique name a model’s column, a typo in the column name, or a String field checked against an integer column, fails to compile instead of failing in production.