Relationships in Laravel Rust, for Eloquent developers
Declaring hasMany, belongsTo, belongsToMany, latestOfMany and hasManyThrough on Rust structs, eager loading, counts, pivot data and attach/sync, shown on a music festival lineup.
- models
- relationships
- database
On this page
- Relationships are fields
- Optional relationships are Option
- No lazy loading, ever
- Constraining what gets loaded
- Already have the model? Use load
- Counts and sums without loading rows
- Filtering by related rows
- Many-to-many, and the pivot data
- attach, detach, sync and toggle
- latestOfMany: one standout row
- hasManyThrough
- Creating related rows
- Named, filtered relationships
- Quick reference
If you’ve used Eloquent for a while, relationships are probably where most of your model code lives: hasMany, belongsTo, a pivot table or two, and a with() on every list page. Laravel Rust keeps all of those ideas and almost all of the names. The difference is where they’re written. A relationship is a typed field on the model struct, not a method, and the compiler checks every column and relationship you mention in a query.
The app in this guide runs the lineup for a music festival. A festival has stages, each stage has performances, an artist can play many festivals, and the booking for each one carries a fee and whether the artist headlines. That’s enough to cover every relationship most apps use.
Relationships are fields
In Eloquent, a relationship is a method that returns a relation object. In Laravel Rust, it’s a field marked with an attribute, and its type says what it holds:
// src/models/stage.rs
use laravel::model::{BelongsTo, HasMany, model};
use crate::models::{Festival, Performance};
#[model]
pub struct Stage {
pub id: i64,
pub festival_id: i64,
pub name: String,
pub capacity: i64,
#[belongs_to]
pub festival: BelongsTo<Festival>,
#[has_many]
pub performances: HasMany<Performance>,
}
The Eloquent version, for comparison:
class Stage extends Model
{
public function festival(): BelongsTo
{
return $this->belongsTo(Festival::class);
}
public function performances(): HasMany
{
return $this->hasMany(Performance::class);
}
}
The key conventions are the ones you know. #[belongs_to] on a field called festival reads festival_id. #[has_many] on Stage expects a stage_id column on performances. When your schema disagrees, override the keys on the attribute: foreign_key and local_key on has_many, foreign_key and owner_key on belongs_to.
Relationship fields aren’t columns. A query returns them unloaded until you ask for them.
Optional relationships are Option
A performance always has a stage, but the artist might not be confirmed when the slot is created. In PHP that’s a nullable artist_id and a ?-> somewhere in a Blade view. Here it’s in the type:
// src/models/performance.rs
use laravel::model::{BelongsTo, model};
use laravel::time::Timestamp;
use crate::models::{Artist, Stage};
#[model]
pub struct Performance {
pub id: i64,
pub stage_id: i64,
pub artist_id: Option<i64>,
pub starts_at: Timestamp,
pub ends_at: Timestamp,
#[belongs_to]
pub stage: BelongsTo<Stage>,
#[belongs_to]
pub artist: BelongsTo<Option<Artist>>,
}
BelongsTo<Option<Artist>> means “there may be no artist”. Leave the Option out on a nullable key and eager loading returns an error when it meets a slot with no artist. The same rule applies to has_one: an artist who may not have a rider uploaded yet is HasOne<Option<Rider>>.
Tip: the compiler handles “TBA” for you. Because the artist is an
Option, every place that shows a performance has to decide what to print when there’s no artist yet. In a Blade template it’s easy to forget the?->and find out on the night.
No lazy loading, ever
This is the change you’ll notice first. Eloquent loads a relationship the moment you touch $stage->performances, which is how N+1 queries end up on list pages. Laravel Rust never loads anything behind your back. You eager-load with with, the same word Eloquent uses:
use crate::models::{Performance, Stage};
let stages = Stage::query()
.filter(Stage::festival_id.eq(festival.id))
.with(Stage::performances.with(Performance::artist))
.order_by(Stage::name)
.get()
.await?;
for stage in &stages {
for slot in &stage.performances {
// slot.artist is loaded too
}
}
That’s three queries however many stages there are: stages, their performances, and the artists. Stage::performances.with(Performance::artist) is the typed version of with('performances.artist'), so a typo in a relationship name is a build error, not an empty list.
If you forget the with, reading stage.performances panics with a message telling you exactly what to add:
Stage::performances isn't loaded; add `.with(Stage::performances)` to the query
It fails on the first request in development, not quietly as a hundred extra queries in production. When a helper can’t know whether its caller loaded something, is_loaded() and try_loaded() check without panicking.
Constraining what gets loaded
The stage screens at the festival only show what’s coming up next. Eloquent does this with a closure inside with(). Laravel Rust passes a closure to the relationship’s query method:
let stages = Stage::query()
.filter(Stage::festival_id.eq(festival.id))
.with(Stage::performances.query(|slots| {
slots
.filter(Performance::starts_at.is_future())
.order_by(Performance::starts_at)
.limit(3)
}))
.get()
.await?;
The limit(3) applies per stage, not to the whole query, so every stage gets its next three acts. That matches Eloquent since Laravel 11; before that, a limit inside an eager-load closure capped the whole result. Always pair a limit with an order_by so the choice is predictable.
Already have the model? Use load
Route model binding hands your handler a Stage. To add relationships afterwards, load works like Eloquent’s load():
use laravel::inertia::{self, Page, props};
use crate::models::{Performance, Stage};
pub async fn show(mut stage: Stage) -> laravel::Result<Page> {
stage
.load(Stage::performances.with(Performance::artist))
.await?;
Ok(inertia::render("Stages/Show", props! { stage }))
}
load_missing only queries what isn’t loaded yet, which is handy in a shared helper that’s sometimes given loaded models and sometimes not.
Counts and sums without loading rows
The programme page shows how many acts each stage has, and the production team wants the total booked capacity. In Eloquent you’d reach for withCount and withSum. Same idea, typed:
let stages = Stage::query()
.filter(Stage::festival_id.eq(festival.id))
.with_count(Stage::performances)
.get()
.await?;
for stage in &stages {
let acts = stage.performances.count();
}
with_sum, with_max, with_min, with_avg and with_exists follow the same pattern, and their return types follow the column: a sum of an integer column is an i64, a max of a timestamp is Option<Timestamp>. On a model you already hold, the load_count, load_sum and friends do the same.
Filtering by related rows
has, whereHas and doesntHave keep their meaning and get snake-case names. The booking team wants every festival that still has an unconfirmed slot:
use crate::models::{Festival, Performance, Stage};
let needs_booking = Festival::query()
.has_where(
Festival::stages,
Stage::performances.exists_where(Performance::artist_id.is_null()),
)
.get()
.await?;
And a leaderboard of the busiest stages, by number of acts:
let busiest = Stage::query()
.order_by(Stage::performances.count().desc())
.limit(5)
.get()
.await?;
Stage::performances.count().ge(10) works inside filter too, so “stages with at least ten acts” is one condition you can combine with & and |.
Many-to-many, and the pivot data
An artist plays many festivals, and a festival books many artists. The join table follows Eloquent’s naming rule, the two snake-case names in alphabetical order: artist_festival. The table has more than two keys, though. Each booking has a fee and a headliner flag, the kind of thing you’d read with $artist->pivot->fee_cents and declare with withPivot().
In Laravel Rust, the extra columns get their own small struct, marked #[join_row]:
// src/models/booking.rs
use laravel::model::join_row;
#[join_row(table = "artist_festival")]
pub struct Booking {
pub fee_cents: i64,
#[default]
pub headliner: bool,
}
Then it’s the second type parameter on both sides of the relationship:
// src/models/festival.rs
#[model]
pub struct Festival {
pub id: i64,
pub name: String,
#[has_many]
pub stages: HasMany<Stage>,
#[belongs_to_many]
pub artists: BelongsToMany<Artist, Booking>,
}
// src/models/artist.rs
#[model]
pub struct Artist {
pub id: i64,
pub name: String,
#[belongs_to_many]
pub festivals: BelongsToMany<Festival, Booking>,
}
After festival.load(Festival::artists), each item reads like an Artist and carries its booking on .join:
for artist in &festival.artists {
if artist.join.headliner {
// artist.name, artist.join.fee_cents
}
}
There’s no $pivot with untyped attributes. If you misspell fee_cents, it doesn’t compile.
attach, detach, sync and toggle
The write methods have the names you already use. Booking an artist with a fee, through db::values!:
use laravel::db;
festival
.artists()
.attach((&artist, db::values! { fee_cents: 2_500_000, headliner: true }))
.await?;
When the booking form submits the full list of artist IDs, sync attaches what’s new and detaches what’s gone, and it reports what changed, which is useful for telling the press office:
let changes = festival.artists().sync(&input.artist_ids).await?;
if !changes.attached.is_empty() {
// queue a "lineup announced" email
}
detach and toggle work as in Eloquent. To change a fee on an existing booking without detaching anything, use update_join_row, the counterpart of updateExistingPivot.
Tip: add the unique index yourself. Like in Laravel PHP, nothing stops the same artist being attached twice unless the database does. Put
table.unique(["artist_id", "festival_id"])in the join table’s migration.
latestOfMany: one standout row
“The headliner’s most recent show” or “a user’s latest order” is a hasOne with latestOfMany() in Eloquent. It’s an option on #[has_one] here, and it can order by a column instead of the ID:
// in Artist
#[has_many]
pub performances: HasMany<Performance>,
#[has_one(latest_of_many = Performance::starts_at)]
pub latest_performance: HasOne<Option<Performance>>,
It’s an Option because a newly signed artist hasn’t played yet. There’s also oldest_of_many and of_many(column, max) for “the biggest” or “the smallest”.
hasManyThrough
Performances don’t have a festival_id, but the festival app constantly needs “every performance at this festival”. Eloquent’s hasManyThrough names the models and keys. Laravel Rust builds the path from two relationships you already declared, so there are no keys to repeat:
// in Festival
#[has_many]
pub stages: HasMany<Stage>,
#[has_many_through(Festival::stages, Stage::performances)]
pub performances: HasManyThrough<Performance>,
Now the whole day’s timetable is one query, and you can filter on the stage in the middle:
let main_stage_tonight = festival
.performances()
.filter(Stage::name.eq("Main Stage") & Performance::starts_at.is_today())
.order_by(Performance::starts_at)
.get()
.await?;
A through relationship is read-only: it can’t know which stage a new performance belongs on. Create through the stage instead, with create!(stage.performances() { .. }).
Creating related rows
create! accepts a relationship query and fills in the foreign key for you, like $stage->performances()->create([...]):
use laravel::model::create;
let slot = create!(stage.performances() {
starts_at: starts_at,
ends_at: ends_at,
artist: &artist,
})
.await?;
Moving a slot to another stage is an update! with the new parent. Laravel updates stage_id and refreshes slot.stage in memory:
use laravel::model::update;
update!(slot { stage: &acoustic_tent }).await?;
Named, filtered relationships
Eloquent apps often grow methods like confirmedPerformances() that wrap a where. Laravel Rust lets you put the condition on the attribute:
// in Stage
#[has_many(filter = !Performance::artist_id.is_null())]
pub confirmed_performances: HasMany<Performance>,
It works everywhere a relationship does: with, with_count, has, and the query method stage.confirmed_performances(). When you create through a filtered relationship, columns constrained with eq are filled in for you. A “not null” filter like this one isn’t, so set the artist yourself.
Quick reference
| Eloquent | Laravel Rust |
|---|---|
hasMany(Stage::class) |
#[has_many] stages: HasMany<Stage> |
belongsTo(Festival::class) |
#[belongs_to] festival: BelongsTo<Festival> |
nullable belongsTo |
BelongsTo<Option<Artist>> |
hasOne(...)->latestOfMany() |
#[has_one(latest_of_many)] |
belongsToMany + withPivot |
BelongsToMany<Artist, Booking> + #[join_row] |
$model->pivot->fee_cents |
artist.join.fee_cents |
hasManyThrough |
#[has_many_through(Festival::stages, Stage::performances)] |
with('stages.performances') |
.with(Festival::stages.with(Stage::performances)) |
withCount('performances') |
.with_count(Stage::performances) |
whereHas |
.has_where(...) |
$stage->performances (lazy) |
loaded only with with or load |
Does Laravel Rust lazy-load relationships like Eloquent?
No. A relationship is only filled when you ask for it with with, load or load_missing. Reading one that wasn't loaded panics with a message naming the eager load to add, so N+1 queries can't creep in unnoticed.
What is the Laravel Rust version of a pivot table?
A #[belongs_to_many] field. The join table follows the same alphabetical naming rule as Eloquent (artist_festival), and extra pivot columns are read through a #[join_row] struct instead of $pivot.
How do I write a nullable belongsTo in Laravel Rust?
Wrap the target in Option: BelongsTo<Option<Stage>>. Use the same for a HasOne that may have no row, or loading fails when the row is missing.