← All guides

· 4 min read

Typed models: Eloquent habits in Laravel Rust

Build a Flight model for an airport departures board: the struct, the queries and the writes, each next to the Eloquent code you'd write today.

  • models
  • database

In Eloquent, a misspelled column or a string where a number belongs shows up when the query runs, sometimes in front of a user. Laravel Rust’s ORM catches both at build time: a model is a Rust struct, and every column has a Rust type.

The example here is an airport departures board: flights, their gates, and how late they’re running. It’s small enough to read in one go, and it has the awkward data real apps have, such as a gate that isn’t assigned yet or a flight that hasn’t left.

The Flight struct

// src/models/flight.rs
use laravel::model::{BelongsTo, model};
use laravel::time::Timestamp;

use crate::models::Airline;

#[model]
pub struct Flight {
    pub id: i64,
    pub airline_id: i64,
    pub number: String,
    pub destination: String,
    pub gate: Option<String>,
    #[default]
    pub delay_minutes: i64,
    pub departed_at: Option<Timestamp>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[belongs_to]
    pub airline: BelongsTo<Airline>,
}

Reading it as an Eloquent developer:

  • gate and departed_at can be empty, and the type says so. Gates are often assigned an hour before boarding, and a flight at the stand hasn’t departed. Nullable columns are Option<T>, so the compiler makes you handle “no gate yet” every time you show one.
  • delay_minutes is #[default]. The database starts it at its default, so you can leave it out when you schedule a flight.
  • airline is a relationship, not a column. It’s the belongsTo method you’d write in PHP, declared as a field.
  • #[model] also derives Clone, Debug and Serialize.

Each model gets its own file in src/models/.

Conventions, and how to bend them

Flight maps to a flights table with an id key, by the same snake-case-plural rule Eloquent uses. When your schema disagrees:

In Eloquent In Laravel Rust
protected $table = 'departures'; #[model(table = "departures")]
protected $primaryKey = 'uuid'; #[key] on that field
getRouteKeyName() returns 'number' #[model(route_key = "number")]
A column named differently #[column("...")] on the field

With route_key = "number", a URL like /flights/RL2041 finds its flight without an extra lookup in the handler.

Tip: a few field names are reserved. #[model] adds functions like query, find, create, update and delete to the struct, so fields can’t use those names. If a legacy table has a column called query, give the field another name and add #[column("query")].

Queries the compiler can read

#[model] gives each field a typed column, such as Flight::delay_minutes. Here’s what the operations desk wants on its screen, flights running at least 30 minutes late that haven’t left yet, written both ways:

// Eloquent
Flight::where('delay_minutes', '>=', 30)
    ->whereNull('departed_at')
    ->orderByDesc('delay_minutes')
    ->limit(20)
    ->get();
// Laravel Rust
let delayed = Flight::query()
    .filter(Flight::delay_minutes.ge(30) & Flight::departed_at.is_null())
    .order_by(Flight::delay_minutes.desc())
    .limit(20)
    .get()
    .await?;

The same typo, delay_minuets instead of delay_minutes, in two places. In Eloquent the query is built from strings, so the mistake only surfaces as a database error when the code runs. In Laravel Rust the column is a typed item on the struct, so cargo build stops with a compile error before anything ships.

Tip: more than eq and gt. Columns also have is_in, between, like, starts_with and contains. Timestamp columns add is_past(), is_future() and is_today(). Join conditions with & and |, flip one with !, and reach for db::raw! when the typed API runs out.

Counting works the same way. How many flights still need a gate?

let waiting_for_gate = Flight::query()
    .filter(Flight::gate.is_null() & Flight::departed_at.is_null())
    .count()
    .await?;

Writing rows

Scheduling a flight goes through the create! macro, which reads like a struct literal. It returns the saved model with its ID, timestamps and defaults filled in:

let flight = create!(Flight {
    number: "RL2041",
    destination: "Lisbon",
    airline: &airline,
})
.await?;

Passing airline: &airline sets airline_id for you, much like associate() does in Eloquent. gate and delay_minutes are left out: one is optional, and the other has a database default.

update! writes only the columns you change, plus updated_at. When the aircraft pushes back:

update!(flight { departed_at: laravel::now() }).await?;

It also works on a whole query, without loading any rows. A storm closes the runway for half an hour, so every flight still on the ground slips by 30 minutes in one statement:

update!(Flight::query().filter(Flight::departed_at.is_null()) {
    delay_minutes += 30,
})
.await?;

Tip: nothing changed, nothing sent. If an update! wouldn’t change any value, no query runs. Eloquent’s save() also skips the query in that case, but update! goes further and skips the model’s hooks and events too.

What you get

Eloquent’s conventions and fluent query style carry over unchanged. On top of that, the compiler rejects unknown columns, mismatched types and unhandled nulls, so a typo in a column name never reaches the departures screen.