Skip to content

Relationships

Models

Database: Model Relationships

Introduction

Tables are often related to each other: a blog post has an author and many comments. Relationships let you declare these connections on your models once, then load, filter, and create related models without writing join queries by hand.

A relationship is a field on a model annotated with an attribute such as #[belongs_to] or #[has_many]. For example, this Post belongs to a user and has many comments:

1// src/models/post.rs
2use laravel::model::{BelongsTo, HasMany, model};
3use laravel::time::Timestamp;
4 
5use crate::models::{Comment, User};
6 
7#[model]
8pub struct Post {
9 pub id: i64,
10 pub user_id: i64,
11 pub title: String,
12 #[default]
13 pub votes: i64,
14 pub published_at: Option<Timestamp>,
15 pub created_at: Timestamp,
16 pub updated_at: Timestamp,
17 
18 #[belongs_to]
19 pub user: BelongsTo<User>,
20 #[has_many]
21 pub comments: HasMany<Comment>,
22}
1// src/models/post.rs
2use laravel::model::{BelongsTo, HasMany, model};
3use laravel::time::Timestamp;
4 
5use crate::models::{Comment, User};
6 
7#[model]
8pub struct Post {
9 pub id: i64,
10 pub user_id: i64,
11 pub title: String,
12 #[default]
13 pub votes: i64,
14 pub published_at: Option<Timestamp>,
15 pub created_at: Timestamp,
16 pub updated_at: Timestamp,
17 
18 #[belongs_to]
19 pub user: BelongsTo<User>,
20 #[has_many]
21 pub comments: HasMany<Comment>,
22}

Once a relationship is declared, you can eager-load it when querying the model:

1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6pub async fn show(Params(id): Params<i64>) -> laravel::Result<Page> {
7 let post = Post::query()
8 .with((Post::user, Post::comments))
9 .find_or_fail(id)
10 .await?;
11 
12 Ok(inertia::render("Posts/Show", props! { post }))
13}
1use laravel::inertia::{self, Page, props};
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6pub async fn show(Params(id): Params<i64>) -> laravel::Result<Page> {
7 let post = Post::query()
8 .with((Post::user, Post::comments))
9 .find_or_fail(id)
10 .await?;
11 
12 Ok(inertia::render("Posts/Show", props! { post }))
13}

Relationships are never lazy-loaded behind the scenes. Load the relationships you need up front with with (or query them directly through methods such as post.comments()), preventing accidental N+1 queries by design.

Declaring relationships

Annotate a model field with the relationship attribute and its matching wrapper type (such as #[belongs_to] with BelongsTo<User> or #[has_many] with HasMany<Comment>). Relationship fields are not database columns, and queries return them unloaded by default until you request them through eager loading.

Has one and has many

A #[has_many] relationship connects a parent model to any number of child records. For example, a user has many posts where each post's user_id column stores the user's primary key. By default, Laravel expects the foreign key on the child table to match the parent struct's snake-case name plus _id (user_id for User, blog_post_id for BlogPost):

1// src/models/user.rs
2use laravel::auth::Authenticatable;
3use laravel::model::{HasMany, model};
4 
5use crate::models::Post;
6 
7#[model]
8#[derive(Authenticatable)]
9pub struct User {
10 pub id: i64,
11 pub name: String,
12 pub email: String,
13 // Other fields...
14 
15 #[has_many]
16 pub posts: HasMany<Post>,
17}
1// src/models/user.rs
2use laravel::auth::Authenticatable;
3use laravel::model::{HasMany, model};
4 
5use crate::models::Post;
6 
7#[model]
8#[derive(Authenticatable)]
9pub struct User {
10 pub id: i64,
11 pub name: String,
12 pub email: String,
13 // Other fields...
14 
15 #[has_many]
16 pub posts: HasMany<Post>,
17}

A #[has_one] relationship follows the same naming convention when at most one related row exists per parent, such as a Profile with a user_id column. Wrap the target type in Option (HasOne<Option<Profile>>) whenever a record may not exist, because loading a non-optional HasOne<Profile> fails if no profile is found:

1#[has_one]
2pub profile: HasOne<Option<Profile>>,
1#[has_one]
2pub profile: HasOne<Option<Profile>>,

If the foreign key or parent key uses a non-default column name, override them with foreign_key and local_key. For example, this matches posts whose author_email column equals the user's email:

1#[has_many(foreign_key = "author_email", local_key = "email")]
2pub authored_posts: HasMany<Post>,
1#[has_many(foreign_key = "author_email", local_key = "email")]
2pub authored_posts: HasMany<Post>,

Belongs to

A #[belongs_to] relationship is the inverse of #[has_one] and #[has_many], linking a foreign key column on the current model to another model's primary key. By convention, Laravel appends _id to the field name, so user reads user_id:

1use laravel::model::{BelongsTo, model};
2 
3use crate::models::User;
4 
5#[model]
6pub struct Post {
7 pub id: i64,
8 pub user_id: i64,
9 pub editor_id: Option<i64>,
10 
11 #[belongs_to]
12 pub user: BelongsTo<User>,
13 #[belongs_to]
14 pub editor: BelongsTo<Option<User>>,
15}
1use laravel::model::{BelongsTo, model};
2 
3use crate::models::User;
4 
5#[model]
6pub struct Post {
7 pub id: i64,
8 pub user_id: i64,
9 pub editor_id: Option<i64>,
10 
11 #[belongs_to]
12 pub user: BelongsTo<User>,
13 #[belongs_to]
14 pub editor: BelongsTo<Option<User>>,
15}

Use BelongsTo<Option<User>> whenever the foreign key is nullable (like editor_id above) or the referenced record might not exist, since eager loading a non-optional BelongsTo<User> returns an error if the parent row is missing.

If your table uses non-standard column names, specify them explicitly. foreign_key is the column on this model, and owner_key is the referenced column on the related model. Here, author matches the post's author_email column against the user's email column:

1#[belongs_to(foreign_key = "author_email", owner_key = "email")]
2pub author: BelongsTo<User>,
1#[belongs_to(foreign_key = "author_email", owner_key = "email")]
2pub author: BelongsTo<User>,

Belongs to many

Many-to-many relationships connect models in both directions through an intermediate join table. For example, a post may have many tags, and each tag may belong to many posts:

1// src/models/post.rs
2use laravel::model::{BelongsToMany, model};
3 
4use crate::models::Tag;
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 // ...
10 
11 #[belongs_to_many]
12 pub tags: BelongsToMany<Tag>,
13}
1// src/models/post.rs
2use laravel::model::{BelongsToMany, model};
3 
4use crate::models::Tag;
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 // ...
10 
11 #[belongs_to_many]
12 pub tags: BelongsToMany<Tag>,
13}
1// src/models/tag.rs
2use laravel::model::model;
3 
4#[model]
5pub struct Tag {
6 pub id: i64,
7 pub name: String,
8}
1// src/models/tag.rs
2use laravel::model::model;
3 
4#[model]
5pub struct Tag {
6 pub id: i64,
7 pub name: String,
8}

By default, Laravel determines the join table name by joining both models' snake-case names in alphabetical order with an underscore (so Post and Tag use post_tag), and expects foreign key columns named after each model plus _id (post_id and tag_id).

Create the join table in a migration, adding a unique index on the pair of foreign keys so the same tag cannot be attached to a post twice:

1// database/migrations/2026_11_07_120000_create_post_tag_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .create("post_tag", |table| {
7 table.foreign_id("post_id").constrained().cascade_on_delete();
8 table.foreign_id("tag_id").constrained().cascade_on_delete();
9 
10 table.unique(["post_id", "tag_id"]);
11 })
12 .await
13}
1// database/migrations/2026_11_07_120000_create_post_tag_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .create("post_tag", |table| {
7 table.foreign_id("post_id").constrained().cascade_on_delete();
8 table.foreign_id("tag_id").constrained().cascade_on_delete();
9 
10 table.unique(["post_id", "tag_id"]);
11 })
12 .await
13}

To customize the join table or column names, pass them as attribute arguments:

1#[belongs_to_many(
2 table = "role_user",
3 foreign_join_key = "member_id",
4 related_join_key = "role_id",
5)]
6pub roles: BelongsToMany<Role>,
1#[belongs_to_many(
2 table = "role_user",
3 foreign_join_key = "member_id",
4 related_join_key = "role_id",
5)]
6pub roles: BelongsToMany<Role>,

Has one of many

When a model has many related rows, you often need easy access to a single standout record, such as a user's most recent order. Declare a #[has_one(latest_of_many)] relationship alongside the #[has_many] relationship:

1// src/models/user.rs
2use laravel::model::{HasMany, HasOne, model};
3 
4use crate::models::Order;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[has_many]
12 pub orders: HasMany<Order>,
13 #[has_one(latest_of_many)]
14 pub latest_order: HasOne<Option<Order>>,
15}
1// src/models/user.rs
2use laravel::model::{HasMany, HasOne, model};
3 
4use crate::models::Order;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[has_many]
12 pub orders: HasMany<Order>,
13 #[has_one(latest_of_many)]
14 pub latest_order: HasOne<Option<Order>>,
15}

latest_of_many selects the order with the largest primary key, while oldest_of_many selects the smallest. Declare the field as HasOne<Option<Order>> unless every user is guaranteed to have an order.

To order by a timestamp or other column instead of the primary key, pass the column to latest_of_many or oldest_of_many:

1#[has_one(latest_of_many = Order::placed_at)]
2pub latest_order: HasOne<Option<Order>>,
1#[has_one(latest_of_many = Order::placed_at)]
2pub latest_order: HasOne<Option<Order>>,

To select a record by the largest or smallest value of a column, such as a user's largest order by price, use of_many with max or min:

1#[has_one(of_many(Order::price, max))]
2pub largest_order: HasOne<Option<Order>>,
1#[has_one(of_many(Order::price, max))]
2pub largest_order: HasOne<Option<Order>>,

Ties are broken by the larger primary key for max and latest_of_many, and by the smaller primary key for min and oldest_of_many. Rows where the ordering column is NULL are excluded. #[morph_one] and #[has_one_through] accept the same options, such as #[morph_one(Image::imageable, latest_of_many)].

A has-one-of-many relationship works like any other #[has_one] with with, with_count, and has_where. Conditions apply specifically to the single selected row, so this query finds users whose latest order is pending rather than users who have any pending order:

1use crate::models::{Order, User};
2 
3let waiting = User::query()
4 .has_where(User::latest_order, Order::status.eq("pending"))
5 .with(User::latest_order)
6 .get()
7 .await?;
1use crate::models::{Order, User};
2 
3let waiting = User::query()
4 .has_where(User::latest_order, Order::status.eq("pending"))
5 .with(User::latest_order)
6 .get()
7 .await?;

Constrained eager loads also apply after the row is chosen: User::latest_order.query(|orders| orders.filter(..)) picks the latest order first and loads it only if it satisfies the filter. If you want the latest order among rows matching a condition (such as the latest paid order), declare a filter on the relationship attribute so the filter runs before the selection.

Has one through and has many through

A through relationship reaches distant rows via an intermediate model. For example, suppose a project has many environments and each environment has many deployments. Even though deployments does not reference projects directly, a project can query all of its deployments through its environments:

1// src/models/project.rs
2use laravel::model::{HasMany, HasManyThrough, model};
3 
4use crate::models::{Deployment, Environment};
5 
6#[model]
7pub struct Project {
8 pub id: i64,
9 pub name: String,
10 
11 #[has_many]
12 pub environments: HasMany<Environment>,
13 #[has_many_through(Project::environments, Environment::deployments)]
14 pub deployments: HasManyThrough<Deployment>,
15}
1// src/models/project.rs
2use laravel::model::{HasMany, HasManyThrough, model};
3 
4use crate::models::{Deployment, Environment};
5 
6#[model]
7pub struct Project {
8 pub id: i64,
9 pub name: String,
10 
11 #[has_many]
12 pub environments: HasMany<Environment>,
13 #[has_many_through(Project::environments, Environment::deployments)]
14 pub deployments: HasManyThrough<Deployment>,
15}
1// src/models/environment.rs
2use laravel::model::{HasMany, model};
3 
4use crate::models::Deployment;
5 
6#[model]
7pub struct Environment {
8 pub id: i64,
9 pub project_id: i64,
10 pub name: String,
11 
12 #[has_many]
13 pub deployments: HasMany<Deployment>,
14}
1// src/models/environment.rs
2use laravel::model::{HasMany, model};
3 
4use crate::models::Deployment;
5 
6#[model]
7pub struct Environment {
8 pub id: i64,
9 pub project_id: i64,
10 pub name: String,
11 
12 #[has_many]
13 pub deployments: HasMany<Deployment>,
14}

#[has_many_through] references two existing relationships: the parent's relationship to the intermediate model, followed by the intermediate model's relationship to the target model. Both steps may be #[has_one], #[has_many], #[morph_one], or #[morph_many] (excluding has-one-of-many relationships). Because keys are inherited from those two relationships, through attributes take no key options.

#[has_one_through] follows the same pattern when at most one related row exists, such as reaching a car's owner through a mechanic's car:

1#[has_one]
2pub car: HasOne<Option<Car>>,
3#[has_one_through(Mechanic::car, Car::owner)]
4pub car_owner: HasOneThrough<Option<Owner>>,
1#[has_one]
2pub car: HasOne<Option<Car>>,
3#[has_one_through(Mechanic::car, Car::owner)]
4pub car_owner: HasOneThrough<Option<Owner>>,

To pick one of many rows through the intermediate model, such as a project's latest deployment across all environments, place the latest_of_many option directly on #[has_one_through] rather than referencing a latest_of_many relationship as the second step:

1#[has_one_through(
2 Project::environments,
3 Environment::deployments,
4 latest_of_many,
5)]
6pub latest_deployment: HasOneThrough<Option<Deployment>>,
1#[has_one_through(
2 Project::environments,
3 Environment::deployments,
4 latest_of_many,
5)]
6pub latest_deployment: HasOneThrough<Option<Deployment>>,

A through relationship queries and eager-loads like #[has_many] or #[has_one]: project.deployments reads loaded deployments, project.deployments() builds a query, and Project::deployments works with with, has, and with_count. Because the query joins the intermediate table, you may also filter on its columns (for example, fetching only deployments in the production environment):

1let deployments = project
2 .deployments()
3 .filter(Environment::name.eq("production"))
4 .get()
5 .await?;
1let deployments = project
2 .deployments()
3 .filter(Environment::name.eq("production"))
4 .get()
5 .await?;

A through relationship is read-only because it cannot determine which intermediate environment should own a new deployment. Create deployments through their environment instead, such as create!(environment.deployments() { .. }). Attempting to create through project.deployments() fails before inserting anything and returns an error naming Environment::deployments.

Filtered relationships

Sometimes you want a named relationship that exposes only a subset of related rows, such as a user's published posts or admin roles. Pass a filter condition to the relationship attribute alongside the unfiltered relationship:

1// src/models/user.rs
2use laravel::model::{HasMany, model};
3 
4use crate::models::Post;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[has_many]
12 pub posts: HasMany<Post>,
13 #[has_many(filter = !Post::published_at.is_null())]
14 pub published_posts: HasMany<Post>,
15}
1// src/models/user.rs
2use laravel::model::{HasMany, model};
3 
4use crate::models::Post;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[has_many]
12 pub posts: HasMany<Post>,
13 #[has_many(filter = !Post::published_at.is_null())]
14 pub published_posts: HasMany<Post>,
15}

A filtered relationship behaves like any #[has_many]: user.published_posts(), with, with_count, has, has_where, and doesnt_have_where all restrict themselves to matching rows automatically. For example, this query retrieves every user with at least one published post along with those published posts:

1use crate::models::User;
2 
3let authors = User::query()
4 .has(User::published_posts)
5 .with(User::published_posts)
6 .get()
7 .await?;
1use crate::models::User;
2 
3let authors = User::query()
4 .has(User::published_posts)
5 .with(User::published_posts)
6 .get()
7 .await?;

The filter expression uses typed columns as in query().filter(...), so column names and value types are verified at compile time. You may combine conditions with & or call a scope such as filter = Post::published(). Every relationship attribute except #[morph_to] supports filter.

Filtering join-row columns

On #[belongs_to_many], filter may also constrain columns on the join row. For example, this relationship returns only roles where the user's role_user membership has level = "admin":

1#[belongs_to_many(filter = Membership::level.eq("admin"))]
2pub admin_roles: BelongsToMany<Role, Membership>,
1#[belongs_to_many(filter = Membership::level.eq("admin"))]
2pub admin_roles: BelongsToMany<Role, Membership>,

Creating and updating through filtered relationships

When you create records through a filtered relationship, Laravel automatically populates any columns constrained with eq so the inserted row satisfies the filter:

1use laravel::model::create;
2 
3// Automatically sets `approved` to `true`...
4let comment = create!(post.approved_comments() { body: "Thanks!" }).await?;
5 
6// Automatically sets `level` to `"admin"` on the join row...
7user.admin_roles().attach(&role).await?;
1use laravel::model::create;
2 
3// Automatically sets `approved` to `true`...
4let comment = create!(post.approved_comments() { body: "Thanks!" }).await?;
5 
6// Automatically sets `level` to `"admin"` on the join row...
7user.admin_roles().attach(&role).await?;

Non-equality filters such as !Post::published_at.is_null() are not populated automatically, so a post created via user.published_posts() remains a draft unless you set published_at yourself.

On a filtered #[belongs_to_many] relationship, write methods (detach, sync, toggle, and update_join_row) affect only join rows matching the filter, leaving other roles untouched:

1// Replaces only the user's admin roles, leaving non-admin roles intact...
2user.admin_roles().sync(&input.role_ids).await?;
1// Replaces only the user's admin roles, leaving non-admin roles intact...
2user.admin_roles().sync(&input.role_ids).await?;

Because a user has only one role_user row per role, calling attach on a role the user already holds at another level violates the unique index. To promote an existing membership instead, update the join row through the unfiltered relationship:

1use laravel::model::joined;
2 
3user.roles()
4 .update_join_row(&role, joined!(Membership { level: "admin" }))
5 .await?;
1use laravel::model::joined;
2 
3user.roles()
4 .update_join_row(&role, joined!(Membership { level: "admin" }))
5 .await?;

Combining filters with other relationships

You may combine filter with has-one-of-many and through relationships:

1// Selects the latest published post...
2#[has_one(latest_of_many, filter = !Post::published_at.is_null())]
3pub latest_published_post: HasOne<Option<Post>>,
4 
5// Fetches comments only on the user's published posts...
6#[has_many_through(User::published_posts, Post::comments)]
7pub published_comments: HasManyThrough<Comment>,
1// Selects the latest published post...
2#[has_one(latest_of_many, filter = !Post::published_at.is_null())]
3pub latest_published_post: HasOne<Option<Post>>,
4 
5// Fetches comments only on the user's published posts...
6#[has_many_through(User::published_posts, Post::comments)]
7pub published_comments: HasManyThrough<Comment>,

Nested route bindings scoped through a filtered relationship also resolve only matching rows.

Calling a relationship as a method returns a query builder already scoped to that parent model. For example, user.posts() returns a db::Builder<Post> restricted to that user's posts, supporting every query builder clause. This handler returns the signed-in user's drafts, newest first:

1use laravel::prelude::*;
2 
3use crate::models::{Post, User};
4 
5pub async fn drafts(
6 Authenticated(user): Authenticated<User>,
7) -> laravel::Result<Json<Vec<Post>>> {
8 let drafts = user
9 .posts()
10 .filter(Post::published_at.is_null())
11 .order_by(Post::created_at.desc())
12 .get()
13 .await?;
14 
15 Ok(Json(drafts))
16}
1use laravel::prelude::*;
2 
3use crate::models::{Post, User};
4 
5pub async fn drafts(
6 Authenticated(user): Authenticated<User>,
7) -> laravel::Result<Json<Vec<Post>>> {
8 let drafts = user
9 .posts()
10 .filter(Post::published_at.is_null())
11 .order_by(Post::created_at.desc())
12 .get()
13 .await?;
14 
15 Ok(Json(drafts))
16}

Counting and deleting related rows follow the same pattern:

1let count = user.posts().count().await?;
2 
3user.posts().filter(Post::votes.lt(-10)).delete().await?;
1let count = user.posts().count().await?;
2 
3user.posts().filter(Post::votes.lt(-10)).delete().await?;

Because Laravel wraps each filter call in its own parentheses, combining conditions with | still restricts results to that user's posts: user.posts().filter(Post::votes.gt(100) | Post::title.eq("Hello")) will never match another user's post.

On a #[belongs_to_many] relationship, the method returns model::ManyToMany, which exposes both join-table writes and shortcuts like get() and count(). To chain additional query clauses such as filter or order_by, call query() first:

1let post = Post::find_or_fail(1).await?;
2 
3let tags = post.tags().query().order_by(Tag::name).get().await?;
1let post = Post::find_or_fail(1).await?;
2 
3let tags = post.tags().query().order_by(Tag::name).get().await?;

You can filter a model query based on whether related records exist using has, has_where, doesnt_have, and doesnt_have_where:

1use crate::models::{Post, User};
2 
3let authors = User::query()
4 .has(User::posts)
5 .get()
6 .await?;
7 
8let popular = User::query()
9 .has_where(User::posts, Post::votes.gt(10))
10 .get()
11 .await?;
12 
13let lurkers = User::query()
14 .doesnt_have(User::posts)
15 .get()
16 .await?;
17 
18let unrecognized = User::query()
19 .doesnt_have_where(User::posts, Post::votes.gt(10))
20 .get()
21 .await?;
1use crate::models::{Post, User};
2 
3let authors = User::query()
4 .has(User::posts)
5 .get()
6 .await?;
7 
8let popular = User::query()
9 .has_where(User::posts, Post::votes.gt(10))
10 .get()
11 .await?;
12 
13let lurkers = User::query()
14 .doesnt_have(User::posts)
15 .get()
16 .await?;
17 
18let unrecognized = User::query()
19 .doesnt_have_where(User::posts, Post::votes.gt(10))
20 .get()
21 .await?;

User::posts.exists() produces the same check as a composable db::Condition, allowing you to combine it with |, &, and ! or nest it inside has_where. For example, these queries find users who either have a post or a @laravel.com address, and users who have at least one post with comments:

1let users = User::query()
2 .filter(User::posts.exists() | User::email.ends_with("@laravel.com"))
3 .get()
4 .await?;
5 
6let commented = User::query()
7 .has_where(User::posts, Post::comments.exists())
8 .get()
9 .await?;
1let users = User::query()
2 .filter(User::posts.exists() | User::email.ends_with("@laravel.com"))
3 .get()
4 .await?;
5 
6let commented = User::query()
7 .has_where(User::posts, Post::comments.exists())
8 .get()
9 .await?;

exists_where builds the condition form of has_where so you can combine it with | or other filters. For example, this finds users who either have a post with more than 10 votes or a @laravel.com address:

1let users = User::query()
2 .filter(
3 User::posts.exists_where(Post::votes.gt(10))
4 | User::email.ends_with("@laravel.com"),
5 )
6 .get()
7 .await?;
1let users = User::query()
2 .filter(
3 User::posts.exists_where(Post::votes.gt(10))
4 | User::email.ends_with("@laravel.com"),
5 )
6 .get()
7 .await?;

When checking for at least one related row isn't enough (such as a leaderboard listing authors with three or more posts), use User::posts.count() and compare it against a number:

1use crate::models::{Post, User};
2 
3let prolific = User::query()
4 .filter(User::posts.count().ge(3))
5 .get()
6 .await?;
1use crate::models::{Post, User};
2 
3let prolific = User::query()
4 .filter(User::posts.count().ge(3))
5 .get()
6 .await?;

To count only related rows matching a condition, use count_where. For example, this finds users who have at least three posts with more than 10 votes:

1let popular = User::query()
2 .filter(User::posts.count_where(Post::votes.gt(10)).ge(3))
3 .get()
4 .await?;
1let popular = User::query()
2 .filter(User::posts.count_where(Post::votes.gt(10)).ge(3))
3 .get()
4 .await?;

Because count comparisons return a standard db::Condition, you can combine them with | or nest them inside has_where. These queries find users who have either exactly one post or a @laravel.com address, and users who have a post with at least five comments:

1let users = User::query()
2 .filter(User::posts.count().eq(1) | User::email.ends_with("@laravel.com"))
3 .get()
4 .await?;
5 
6let discussed = User::query()
7 .has_where(User::posts, Post::comments.count().ge(5))
8 .get()
9 .await?;
1let users = User::query()
2 .filter(User::posts.count().eq(1) | User::email.ends_with("@laravel.com"))
3 .get()
4 .await?;
5 
6let discussed = User::query()
7 .has_where(User::posts, Post::comments.count().ge(5))
8 .get()
9 .await?;

You may also pass a relationship count to order_by to sort models by how many related records they have. For example, this retrieves the ten users with the most posts:

1let busiest = User::query()
2 .order_by(User::posts.count().desc())
3 .limit(10)
4 .get()
5 .await?;
1let busiest = User::query()
2 .order_by(User::posts.count().desc())
3 .limit(10)
4 .get()
5 .await?;

Relationship counts support eq, ne, lt, le, gt, ge, and between with whole numbers.

Eager loading

Suppose you list 25 posts alongside each author's name. Querying each post's author inside the loop would run 26 queries: one for the posts and one per author. Eager loading reduces this to two queries. Pass a relationship to with to load it across every model returned by the query:

1use crate::models::Post;
2 
3let posts = Post::query().with(Post::user).get().await?;
4 
5for post in &posts {
6 println!("{} by {}", post.title, post.user.name);
7}
1use crate::models::Post;
2 
3let posts = Post::query().with(Post::user).get().await?;
4 
5for post in &posts {
6 println!("{} by {}", post.title, post.user.name);
7}

Laravel runs the posts query first, then runs a single query to fetch all referenced users and populates each post's user field. To eager-load multiple relationships at once, pass them as a tuple (one query runs per relationship):

1let posts = Post::query()
2 .with((Post::user, Post::comments))
3 .get()
4 .await?;
1let posts = Post::query()
2 .with((Post::user, Post::comments))
3 .get()
4 .await?;

Nested eager loading

To eager-load relationships of related models, chain with on the relationship descriptor. For example, this loads every user's posts along with each post's comments and tags:

1use crate::models::{Post, User};
2 
3let users = User::query()
4 .with(User::posts.with((Post::comments, Post::tags)))
5 .get()
6 .await?;
1use crate::models::{Post, User};
2 
3let users = User::query()
4 .with(User::posts.with((Post::comments, Post::tags)))
5 .get()
6 .await?;

Constraining eager loads

To filter, sort, or limit the related records fetched during eager loading, pass a closure to the relationship's query method. For example, this loads each user's three most recent published posts:

1use crate::models::{Post, User};
2 
3let users = User::query()
4 .with(User::posts.query(|posts| {
5 posts
6 .filter(!Post::published_at.is_null())
7 .order_by(Post::published_at.desc())
8 .limit(3)
9 }))
10 .get()
11 .await?;
1use crate::models::{Post, User};
2 
3let users = User::query()
4 .with(User::posts.query(|posts| {
5 posts
6 .filter(!Post::published_at.is_null())
7 .order_by(Post::published_at.desc())
8 .limit(3)
9 }))
10 .get()
11 .await?;

limit and offset inside an eager load apply per parent record rather than globally, so every user receives up to three posts. Always include an order_by when limiting an eager load so the selection is deterministic.

You may chain with and query in either order and nest constraints at multiple levels. For example, this loads each user's three most recent published posts along with only the approved comments on those posts:

1use crate::models::{Comment, Post, User};
2 
3let users = User::query()
4 .with(
5 User::posts
6 .query(|posts| {
7 posts
8 .filter(!Post::published_at.is_null())
9 .order_by(Post::published_at.desc())
10 .limit(3)
11 })
12 .with(Post::comments.query(|comments| {
13 comments.filter(Comment::approved.eq(true))
14 })),
15 )
16 .get()
17 .await?;
1use crate::models::{Comment, Post, User};
2 
3let users = User::query()
4 .with(
5 User::posts
6 .query(|posts| {
7 posts
8 .filter(!Post::published_at.is_null())
9 .order_by(Post::published_at.desc())
10 .limit(3)
11 })
12 .with(Post::comments.query(|comments| {
13 comments.filter(Comment::approved.eq(true))
14 })),
15 )
16 .get()
17 .await?;

To retrieve the number of related records without loading the records themselves, call with_count on the query and read the result with count() on the relationship field:

1use crate::models::Post;
2 
3let posts = Post::query().with_count(Post::comments).get().await?;
4 
5for post in &posts {
6 println!("{} has {} comments", post.title, post.comments.count());
7}
1use crate::models::Post;
2 
3let posts = Post::query().with_count(Post::comments).get().await?;
4 
5for post in &posts {
6 println!("{} has {} comments", post.title, post.comments.count());
7}

Pass a constrained relationship to count only a subset of related rows. For example, this counts each post's approved comments:

1use crate::models::{Comment, Post};
2 
3let posts = Post::query()
4 .with_count(Post::comments.query(|comments| {
5 comments.filter(Comment::approved.eq(true))
6 }))
7 .get()
8 .await?;
1use crate::models::{Comment, Post};
2 
3let posts = Post::query()
4 .with_count(Post::comments.query(|comments| {
5 comments.filter(Comment::approved.eq(true))
6 }))
7 .get()
8 .await?;

Sums, extremes, averages, and existence

Alongside counts, Laravel can compute sums, averages, minimums, and maximums over a related model's columns without loading the related rows. For example, an author directory can fetch each user's total post votes and most recent publication timestamp by calling with_sum, with_max, with_min, or with_avg and reading the value from the matching method on the relationship field:

1use laravel::time::Timestamp;
2 
3use crate::models::{Post, User};
4 
5let users = User::query()
6 .with_sum(User::posts, Post::votes)
7 .with_max(User::posts, Post::published_at)
8 .get()
9 .await?;
10 
11for user in &users {
12 let votes: i64 = user.posts.sum(Post::votes);
13 let latest: Option<Timestamp> = user.posts.max(Post::published_at);
14}
1use laravel::time::Timestamp;
2 
3use crate::models::{Post, User};
4 
5let users = User::query()
6 .with_sum(User::posts, Post::votes)
7 .with_max(User::posts, Post::published_at)
8 .get()
9 .await?;
10 
11for user in &users {
12 let votes: i64 = user.posts.sum(Post::votes);
13 let latest: Option<Timestamp> = user.posts.max(Post::published_at);
14}

The return type depends on the aggregate and column type:

Method Columns Return type
sum(column) Numeric columns i64 for integers, f64 for floats, Decimal for decimals (0 when no related rows exist)
avg(column) Numeric columns Option<f64>
max(column), min(column) Numbers, text, dates, and times Option<T> for the column's inner type

Use with_exists to check whether any related row exists and read the boolean via exists(). Like with_count, it accepts a single relationship or a tuple:

1let users = User::query()
2 .with_exists((User::posts, User::profile))
3 .get()
4 .await?;
5 
6let writers = users
7 .iter()
8 .filter(|user| user.posts.exists())
9 .count();
1let users = User::query()
2 .with_exists((User::posts, User::profile))
3 .get()
4 .await?;
5 
6let writers = users
7 .iter()
8 .filter(|user| user.posts.exists())
9 .count();

Constrained relationships work with every aggregate method, and you may also aggregate join-row columns such as with_max(User::roles, Membership::expires_at). A single relationship field can store multiple computed aggregates simultaneously (for example, both with_count(User::posts) and with_sum(User::posts, Post::votes)).

Because model queries hydrate every column of the model, they do not expose select or add_select. These relationship aggregate methods cover most summary views; for arbitrary custom projections, query db::table into a struct deriving db::FromRow.

Loading into models you already have

When you already hold a model (such as one injected via route model binding) or a Vec of models, call load with any relationship or tuple accepted by with:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(mut user: User) -> laravel::Result<Page> {
6 user.load(User::posts.with(Post::comments)).await?;
7 
8 Ok(inertia::render("Users/Show", props! { user }))
9}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(mut user: User) -> laravel::Result<Page> {
6 user.load(User::posts.with(Post::comments)).await?;
7 
8 Ok(inertia::render("Users/Show", props! { user }))
9}
1let mut users = User::all().await?;
2 
3users.load((User::posts, User::profile)).await?;
1let mut users = User::all().await?;
2 
3users.load((User::posts, User::profile)).await?;

You may also constrain load with .query(..), as shown in constrained eager loads:

1user.load(User::posts.query(|posts| {
2 posts
3 .filter(Post::published_at.is_not_null())
4 .order_by(Post::published_at.desc())
5 .limit(5)
6}))
7.await?;
1user.load(User::posts.query(|posts| {
2 posts
3 .filter(Post::published_at.is_not_null())
4 .order_by(Post::published_at.desc())
5 .limit(5)
6}))
7.await?;

load always executes its query and replaces any previously loaded values. When some models may already have a relationship loaded, use load_missing instead. For example, if a helper renders posts with their authors and some callers have already eager-loaded Post::user, load_missing queries only the missing authors and skips the query altogether when every post already has one:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn render_feed(mut posts: Vec<Post>) -> laravel::Result<Page> {
6 posts.load_missing(Post::user).await?;
7 
8 Ok(inertia::render("Posts/Feed", props! { posts }))
9}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn render_feed(mut posts: Vec<Post>) -> laravel::Result<Page> {
6 posts.load_missing(Post::user).await?;
7 
8 Ok(inertia::render("Posts/Feed", props! { posts }))
9}

Nested relationships also skip already-loaded relations at each level. This loads posts for users that haven't loaded them yet, then loads comments for every post missing them, including posts that were already loaded:

1users.load_missing(User::posts.with(Post::comments)).await?;
1users.load_missing(User::posts.with(Post::comments)).await?;

Loading counts and aggregates

load_count counts related rows on models you already hold, mirroring with_count on queries. load_exists, load_sum, load_max, load_min, and load_avg also work on single models and Vec slices. This handler shows a user from route model binding with their post count and total votes:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(mut user: User) -> laravel::Result<Page> {
6 user.load_count(User::posts).await?;
7 user.load_sum(User::posts, Post::votes).await?;
8 
9 Ok(inertia::render("Users/Show", props! { user }))
10}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::{Post, User};
4 
5pub async fn show(mut user: User) -> laravel::Result<Page> {
6 user.load_count(User::posts).await?;
7 user.load_sum(User::posts, Post::votes).await?;
8 
9 Ok(inertia::render("Users/Show", props! { user }))
10}

You may also call these loaders on an already-loaded relationship field, for example counting each post's comments after loading a user's posts:

1user.load(User::posts).await?;
2user.posts.load_count(Post::comments).await?;
1user.load(User::posts).await?;
2user.posts.load_count(Post::comments).await?;

Having a count from with_count does not mark the relationship itself as loaded, so load_missing will still load the related models. Constraints passed to load_missing apply only to models that do not yet have the relationship loaded; models that already hold loaded records keep them unchanged unless you call load.

Reading loaded relationships

Once loaded, a relationship field dereferences directly to its underlying value (User for BelongsTo<User>, &[Comment] for HasMany<Comment>):

1let post = Post::query().with((Post::user, Post::comments)).find_or_fail(1).await?;
2 
3let author = &post.user.name;
4let count = post.comments.len();
5 
6for comment in &post.comments {
7 // ...
8}
1let post = Post::query().with((Post::user, Post::comments)).find_or_fail(1).await?;
2 
3let author = &post.user.name;
4let count = post.comments.len();
5 
6for comment in &post.comments {
7 // ...
8}

Accessing a relationship that has not been loaded panics with a message naming the missing eager load:

1Post::comments isn't loaded; add `.with(Post::comments)` to the query
1Post::comments isn't loaded; add `.with(Post::comments)` to the query

When a relationship might or might not have been loaded, check is_loaded() or read it safely with try_loaded(), which returns Option<&T> without panicking:

1if post.user.is_loaded() {
2 println!("Author: {}", post.user.name);
3}
4 
5if let Some(comments) = post.comments.try_loaded() {
6 println!("{} comments loaded", comments.len());
7}
1if post.user.is_loaded() {
2 println!("Author: {}", post.user.name);
3}
4 
5if let Some(comments) = post.comments.try_loaded() {
6 println!("{} comments loaded", comments.len());
7}

If you loaded a relationship rather than calling with_count or with_exists, post.comments.count() and post.comments.exists() still work by inspecting the loaded records. Reading any other aggregate (such as sum, max, min, or avg) that was not requested panics with the exact call to add, such as add `.with_max(User::posts, Post::votes)` to the query.

To insert a child record belonging to an existing parent, pass the parent's relationship query to create!. Laravel populates the foreign key (post_id) automatically:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn store(
7 post: Post,
8 Authenticated(user): Authenticated<User>,
9) -> laravel::Result<Redirect> {
10 create!(post.comments() { body: "First!", user: &user }).await?;
11 
12 Ok(Redirect::back())
13}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn store(
7 post: Post,
8 Authenticated(user): Authenticated<User>,
9) -> laravel::Result<Redirect> {
10 create!(post.comments() { body: "First!", user: &user }).await?;
11 
12 Ok(Redirect::back())
13}

Relationship creates also accept a fill struct (create!(post.comments() { ..input })) or a list of records:

1let comments = create!([
2 post.comments() { body: "One", user: &user },
3 post.comments() { body: "Two", user: &user },
4])
5.await?;
1let comments = create!([
2 post.comments() { body: "One", user: &user },
3 post.comments() { body: "Two", user: &user },
4])
5.await?;

On a #[belongs_to_many] relationship, create! inserts both the new related model and its linking row in the join table:

1let tag = create!(post.tags() { name: "Rust" }).await?;
1let tag = create!(post.tags() { name: "Rust" }).await?;

When you need to build the insert dynamically, call post.comments().create() for a pre-populated create builder, or create_many to insert a list of builders or fill structs inside one transaction:

1let comment = post
2 .comments()
3 .create()
4 .body("Nice post!")
5 .user(&user)
6 .await?;
7 
8let tags = post
9 .tags()
10 .create_many([
11 Tag::create().name("Rust"),
12 Tag::create().name("Laravel"),
13 ])
14 .await?;
1let comment = post
2 .comments()
3 .create()
4 .body("Nice post!")
5 .user(&user)
6 .await?;
7 
8let tags = post
9 .tags()
10 .create_many([
11 Tag::create().name("Rust"),
12 Tag::create().name("Laravel"),
13 ])
14 .await?;

You may also insert a parent and its related models in a single create! call by nesting a struct literal for the relationship field. All inserts run in one transaction and hydrate the relationship in memory:

1let post = create!(Post {
2 title: "Hello",
3 user: User {
4 name: "Abigail",
5 email: "[email protected]",
6 password: "secret",
7 },
8})
9.await?;
1let post = create!(Post {
2 title: "Hello",
3 user: User {
4 name: "Abigail",
5 email: "[email protected]",
6 password: "secret",
7 },
8})
9.await?;

To learn more about nested and batched creates, check out Creating related models together.

To reassign a #[belongs_to] relationship to a different parent (such as transferring a post to another author), assign the new parent model inside update!:

1use laravel::model::update;
2 
3update!(post { user: &user }).await?;
1use laravel::model::update;
2 
3update!(post { user: &user }).await?;

Laravel updates user_id in the database and refreshes post.user in memory so you can read it immediately without another query.

Attaching and syncing join rows

Unlike one-to-many relationships where a foreign key lives directly on the child table, many-to-many relationships store their links in an intermediate join table (such as post_tag connecting posts and tags). Rather than inserting and deleting rows in that join table manually, Laravel provides helper methods directly on your #[belongs_to_many] relationship for attaching, detaching, syncing, toggling, and updating join rows.

To link one or more related records to a model, pass a model, a primary key, or an array, Vec, or slice of either to attach:

1post.tags().attach(&rust).await?;
2post.tags().attach([&rust, &release]).await?;
3post.tags().attach([1, 2]).await?;
1post.tags().attach(&rust).await?;
2post.tags().attach([&rust, &release]).await?;
3post.tags().attach([1, 2]).await?;

To remove links from the join table without deleting the related models themselves, call detach. It accepts the same arguments as attach and returns the number of removed join rows:

1post.tags().detach(&release).await?;
2post.tags().detach([1, 2]).await?;
1post.tags().detach(&release).await?;
2post.tags().detach([1, 2]).await?;

When a form submits the complete set of related records a model should have, such as the tags selected when editing a post, use sync. It attaches any IDs that are not yet linked and detaches any existing links omitted from the list:

1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct PostTags {
8 pub tag_ids: Vec<i64>,
9}
10 
11pub async fn update(post: Post, Valid(input): Valid<PostTags>) -> laravel::Result<Redirect> {
12 post.tags().sync(&input.tag_ids).await?;
13 
14 Ok(Redirect::back())
15}
1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct PostTags {
8 pub tag_ids: Vec<i64>,
9}
10 
11pub async fn update(post: Post, Valid(input): Valid<PostTags>) -> laravel::Result<Redirect> {
12 post.tags().sync(&input.tag_ids).await?;
13 
14 Ok(Redirect::back())
15}

If you want to flip the link state for a set of records, detaching any that are currently linked and attaching any that are not, call toggle:

1post.tags().toggle([&rust, &release]).await?;
1post.tags().toggle([&rust, &release]).await?;

Both sync and toggle return a model::SyncChanges struct listing the attached, detached, and updated keys:

1let changes = post.tags().sync([2, 3]).await?;
2 
3if !changes.attached.is_empty() {
4 // Notify followers of the new tags...
5}
1let changes = post.tags().sync([2, 3]).await?;
2 
3if !changes.attached.is_empty() {
4 // Notify followers of the new tags...
5}

To set extra columns on join rows as you link them, pair each model or key with db::values!. attach and toggle write those columns on newly inserted rows, while sync updates them on every retained row as well:

1use laravel::db;
2 
3post.tags()
4 .attach((&rust, db::values! { pinned: true }))
5 .await?;
6 
7post.tags()
8 .sync([
9 (&release, db::values! { pinned: true }),
10 (&rust, db::values! { pinned: false }),
11 ])
12 .await?;
1use laravel::db;
2 
3post.tags()
4 .attach((&rust, db::values! { pinned: true }))
5 .await?;
6 
7post.tags()
8 .sync([
9 (&release, db::values! { pinned: true }),
10 (&rust, db::values! { pinned: false }),
11 ])
12 .await?;

To update extra columns on an existing join row without attaching or detaching any records, call update_join_row:

1post.tags()
2 .update_join_row(&rust, db::values! { pinned: true })
3 .await?;
1post.tags()
2 .update_join_row(&rust, db::values! { pinned: true })
3 .await?;

To read these columns back with the related models and have the compiler check their names and types, describe them in a join row.

Defining join-row models

A join table often holds more than the two foreign keys. For example, a user's role may expire via an expires_at column on role_user. To read extra join columns alongside related models, define a struct annotated with #[join_row] containing a field for each column:

1// src/models/membership.rs
2use laravel::model::join_row;
3use laravel::time::Timestamp;
4 
5#[join_row(table = "role_user")]
6pub struct Membership {
7 pub level: String,
8 pub expires_at: Option<Timestamp>,
9 pub created_at: Timestamp,
10 pub updated_at: Timestamp,
11}
1// src/models/membership.rs
2use laravel::model::join_row;
3use laravel::time::Timestamp;
4 
5#[join_row(table = "role_user")]
6pub struct Membership {
7 pub level: String,
8 pub expires_at: Option<Timestamp>,
9 pub created_at: Timestamp,
10 pub updated_at: Timestamp,
11}

List only the join-table columns you care about. By convention, the table name is the snake-case struct name (such as role_user for RoleUser); use #[join_row(table = "..")] to specify a different table name. Field types, #[column("..")], #[default], and created_at / updated_at timestamps work like model fields, and #[join_row] automatically derives Clone, Debug, and Serialize so join attributes serialize under a join key.

When defining the relationship on the model, pass the join-row struct as the second type parameter on both sides of the relationship (the relationship automatically inherits the table name from the join row):

1// src/models/user.rs
2use laravel::model::{BelongsToMany, model};
3 
4use crate::models::{Membership, Role};
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[belongs_to_many]
12 pub roles: BelongsToMany<Role, Membership>,
13}
1// src/models/user.rs
2use laravel::model::{BelongsToMany, model};
3 
4use crate::models::{Membership, Role};
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 
11 #[belongs_to_many]
12 pub roles: BelongsToMany<Role, Membership>,
13}
1// src/models/role.rs
2#[model]
3pub struct Role {
4 pub id: i64,
5 pub name: String,
6 
7 #[belongs_to_many]
8 pub users: BelongsToMany<User, Membership>,
9}
1// src/models/role.rs
2#[model]
3pub struct Role {
4 pub id: i64,
5 pub name: String,
6 
7 #[belongs_to_many]
8 pub users: BelongsToMany<User, Membership>,
9}

Accessing join-row attributes

Eager loading populates each item of user.roles as a model::Joined<Role, Membership>, which dereferences to Role and exposes the join-table attributes on .join:

1pub async fn show(mut user: User) -> laravel::Result<Page> {
2 user.load(User::roles).await?;
3 
4 let admin_until = user
5 .roles
6 .iter()
7 .find(|role| role.name == "admin")
8 .and_then(|role| role.join.expires_at);
9 
10 Ok(inertia::render("Users/Show", props! { user, admin_until }))
11}
1pub async fn show(mut user: User) -> laravel::Result<Page> {
2 user.load(User::roles).await?;
3 
4 let admin_until = user
5 .roles
6 .iter()
7 .find(|role| role.name == "admin")
8 .and_then(|role| role.join.expires_at);
9 
10 Ok(inertia::render("Users/Show", props! { user, admin_until }))
11}

Because Joined<Role, Membership> dereferences to Role, role fields and methods work directly on it, &Joined<Role, Membership> passes anywhere &Role is expected, and relationship writes accept it directly:

1let role = &user.roles[0];
2 
3println!("{} ({})", role.name, role.join.level);
4 
5audit_role(role); // accepts `&Role`
6 
7user.roles().detach(role).await?;
1let role = &user.roles[0];
2 
3println!("{} ({})", role.name, role.join.level);
4 
5audit_role(role); // accepts `&Role`
6 
7user.roles().detach(role).await?;

Querying join rows directly

To query a user's roles together with their join rows without hydrating them onto user (for example, when paginating a long list), call joined() on the relationship, chain optional clauses with query, and finish with get, first, paginate, simple_paginate, or cursor. For example, this query paginates the user's roles 15 at a time, ordered by when each membership was created, and returns each Role paired with its Membership join row:

1let roles = user
2 .roles()
3 .joined()
4 .query(|roles| roles.order_by(Membership::created_at.desc()))
5 .paginate(15)
6 .await?;
1let roles = user
2 .roles()
3 .joined()
4 .query(|roles| roles.order_by(Membership::created_at.desc()))
5 .paginate(15)
6 .await?;

find and find_or_fail fetch a single attached model along with its join row by primary key, with find returning None if the records are not linked:

1let expires_at = user
2 .roles()
3 .joined()
4 .find(2)
5 .await?
6 .and_then(|role| role.join.expires_at);
1let expires_at = user
2 .roles()
3 .joined()
4 .find(2)
5 .await?
6 .and_then(|role| role.join.expires_at);

Calling user.roles().get() directly continues to return plain Role models without join rows.

Filtering and ordering by join-row columns

#[join_row] generates typed column constants (such as Membership::expires_at) that work in any query joining the join table: relationship queries, constrained eager loads, has_where, doesnt_have_where, and with_count. You may define reusable query scopes and instance methods directly on the join-row struct:

1use laravel::db::Condition;
2 
3impl Membership {
4 /// Memberships that haven't expired...
5 pub fn current() -> Condition {
6 Membership::expires_at.is_null() | Membership::expires_at.gt(laravel::now())
7 }
8 
9 /// Whether this membership hasn't expired...
10 pub fn is_current(&self) -> bool {
11 self.expires_at
12 .is_none_or(|expires_at| expires_at > laravel::now().timestamp())
13 }
14}
15 
16// Load the user's active roles, newest first...
17let user = User::query()
18 .with(User::roles.query(|roles| {
19 roles
20 .filter(Membership::current())
21 .order_by(Membership::created_at.desc())
22 }))
23 .find_or_fail(1)
24 .await?;
25 
26// Find users with an active admin role...
27let admins = User::query()
28 .has_where(User::roles, Role::name.eq("admin") & Membership::current())
29 .get()
30 .await?;
31 
32// Find users with no active roles...
33let lapsed = User::query()
34 .doesnt_have_where(User::roles, Membership::current())
35 .get()
36 .await?;
1use laravel::db::Condition;
2 
3impl Membership {
4 /// Memberships that haven't expired...
5 pub fn current() -> Condition {
6 Membership::expires_at.is_null() | Membership::expires_at.gt(laravel::now())
7 }
8 
9 /// Whether this membership hasn't expired...
10 pub fn is_current(&self) -> bool {
11 self.expires_at
12 .is_none_or(|expires_at| expires_at > laravel::now().timestamp())
13 }
14}
15 
16// Load the user's active roles, newest first...
17let user = User::query()
18 .with(User::roles.query(|roles| {
19 roles
20 .filter(Membership::current())
21 .order_by(Membership::created_at.desc())
22 }))
23 .find_or_fail(1)
24 .await?;
25 
26// Find users with an active admin role...
27let admins = User::query()
28 .has_where(User::roles, Role::name.eq("admin") & Membership::current())
29 .get()
30 .await?;
31 
32// Find users with no active roles...
33let lapsed = User::query()
34 .doesnt_have_where(User::roles, Membership::current())
35 .get()
36 .await?;

Once user.roles is loaded, is_current lets you filter expired roles in memory:

1let expired: Vec<&str> = user
2 .roles
3 .iter()
4 .filter(|role| !role.join.is_current())
5 .map(|role| role.name.as_str())
6 .collect();
1let expired: Vec<&str> = user
2 .roles
3 .iter()
4 .filter(|role| !role.join.is_current())
5 .map(|role| role.name.as_str())
6 .collect();

To check whether a user holds an active role without loading all of their roles (for instance inside an authorization policy), filter the relationship query and call exists:

1let is_admin = user
2 .roles()
3 .query()
4 .filter(Role::name.eq("admin") & Membership::current())
5 .exists()
6 .await?;
1let is_admin = user
2 .roles()
3 .query()
4 .filter(Role::name.eq("admin") & Membership::current())
5 .exists()
6 .await?;

latest, oldest, pluck, and value accept join-row columns as well:

1let newest: Vec<String> = user
2 .roles()
3 .query()
4 .latest(Membership::created_at)
5 .pluck(Role::name)
6 .await?;
1let newest: Vec<String> = user
2 .roles()
3 .query()
4 .latest(Membership::created_at)
5 .pluck(Role::name)
6 .await?;

Writing join-row columns

To populate join-table columns in attach, sync, toggle, or update_join_row with compile-time type checking, pair each related model with joined!. Standard Rust field shorthand works here as well:

1use laravel::model::joined;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct GrantRole {
7 pub level: String,
8}
9 
10pub async fn grant(
11 user: User,
12 role: Role,
13 Valid(GrantRole { level }): Valid<GrantRole>,
14) -> laravel::Result<Redirect> {
15 user.roles()
16 .attach((
17 &role,
18 joined!(Membership {
19 level,
20 expires_at: laravel::now().plus(30.days()),
21 }),
22 ))
23 .await?;
24 
25 Ok(Redirect::back())
26}
1use laravel::model::joined;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct GrantRole {
7 pub level: String,
8}
9 
10pub async fn grant(
11 user: User,
12 role: Role,
13 Valid(GrantRole { level }): Valid<GrantRole>,
14) -> laravel::Result<Redirect> {
15 user.roles()
16 .attach((
17 &role,
18 joined!(Membership {
19 level,
20 expires_at: laravel::now().plus(30.days()),
21 }),
22 ))
23 .await?;
24 
25 Ok(Redirect::back())
26}

Syncing and updating join rows

Pass an array of pairs to sync, or pass the related model and joined! values to update_join_row:

1user.roles()
2 .sync([
3 (1, joined!(Membership { level: "owner", expires_at: None })),
4 (
5 2,
6 joined!(Membership {
7 level: "member",
8 expires_at: laravel::now().plus(7.days()),
9 }),
10 ),
11 ])
12 .await?;
13 
14user.roles()
15 .update_join_row(&role, joined!(Membership { expires_at: None }))
16 .await?;
1user.roles()
2 .sync([
3 (1, joined!(Membership { level: "owner", expires_at: None })),
4 (
5 2,
6 joined!(Membership {
7 level: "member",
8 expires_at: laravel::now().plus(7.days()),
9 }),
10 ),
11 ])
12 .await?;
13 
14user.roles()
15 .update_join_row(&role, joined!(Membership { expires_at: None }))
16 .await?;

When syncing a dynamic list of roles with join-row values, collect the pairs into a Vec before passing them to sync:

1let memberships: Vec<_> = input
2 .roles
3 .into_iter()
4 .map(|role| {
5 (
6 role.id,
7 joined!(Membership {
8 level: role.level,
9 expires_at: role.expires_at,
10 }),
11 )
12 })
13 .collect();
14 
15user.roles().sync(memberships).await?;
1let memberships: Vec<_> = input
2 .roles
3 .into_iter()
4 .map(|role| {
5 (
6 role.id,
7 joined!(Membership {
8 level: role.level,
9 expires_at: role.expires_at,
10 }),
11 )
12 })
13 .collect();
14 
15user.roles().sync(memberships).await?;

Partial updates with fill structs

For partial updates such as PATCH forms, define a fill struct targeting the join row with Sometimes fields and spread ..input at the end of joined! so omitted fields keep their existing values:

1use laravel::prelude::*;
2use laravel::validation::Sometimes;
3 
4#[laravel::input(fills = Membership)]
5#[validate(anyone)]
6pub struct EditMembership {
7 pub level: Sometimes<String>,
8 pub expires_at: Sometimes<Option<Timestamp>>,
9}
10 
11pub async fn update(
12 user: User,
13 role: Role,
14 Valid(input): Valid<EditMembership>,
15) -> laravel::Result<Redirect> {
16 user.roles().update_join_row(&role, joined!(Membership { ..input })).await?;
17 
18 Ok(Redirect::back())
19}
1use laravel::prelude::*;
2use laravel::validation::Sometimes;
3 
4#[laravel::input(fills = Membership)]
5#[validate(anyone)]
6pub struct EditMembership {
7 pub level: Sometimes<String>,
8 pub expires_at: Sometimes<Option<Timestamp>>,
9}
10 
11pub async fn update(
12 user: User,
13 role: Role,
14 Valid(input): Valid<EditMembership>,
15) -> laravel::Result<Redirect> {
16 user.roles().update_join_row(&role, joined!(Membership { ..input })).await?;
17 
18 Ok(Redirect::back())
19}

Building join-row values dynamically

When the join columns to write depend on runtime logic, call Membership::values() for a fluent builder with column setters and .fill(input), which can be passed anywhere joined! is accepted:

1let mut values = Membership::values().fill(input);
2 
3if role.name == "admin" {
4 values = values.expires_at(laravel::now().plus(30.days()));
5}
6 
7user.roles().update_join_row(&role, values).await?;
1let mut values = Membership::values().fill(input);
2 
3if role.name == "admin" {
4 values = values.expires_at(laravel::now().plus(30.days()));
5}
6 
7user.roles().update_join_row(&role, values).await?;

Creating and attaching in a transaction

To create a new role and attach it with join-row columns atomically, wrap both writes in a transaction:

1use laravel::db;
2use laravel::model::create;
3 
4let role = db::transaction(async |_| {
5 let role = create!(Role { name: "Billing" }).await?;
6 
7 user.roles().attach((&role, joined!(Membership { level: "owner" }))).await?;
8 
9 Ok(role)
10})
11.await?;
1use laravel::db;
2use laravel::model::create;
3 
4let role = db::transaction(async |_| {
5 let role = create!(Role { name: "Billing" }).await?;
6 
7 user.roles().attach((&role, joined!(Membership { level: "owner" }))).await?;
8 
9 Ok(role)
10})
11.await?;

Polymorphic relationships

Sometimes one model can attach to multiple parent types, such as users commenting on both blog posts and videos. Rather than creating separate comments tables, a polymorphic relationship stores every comment in one table, recording each parent's type and key.

The comments table holds a type column and a key column for the parent. The schema builder's morphs helper adds both columns and indexes the pair:

1tx.schema()
2 .create("comments", |table| {
3 table.id();
4 table.text("body");
5 table.morphs("commentable");
6 table.timestamps();
7 })
8 .await?;
1tx.schema()
2 .create("comments", |table| {
3 table.id();
4 table.text("body");
5 table.morphs("commentable");
6 table.timestamps();
7 })
8 .await?;

morphs("commentable") adds a string commentable_type column and a big integer commentable_id column. Use uuid_morphs or ulid_morphs when parents use UUID or ULID keys, and the nullable_ variants when the parent is optional.

Declaring polymorphic relationships

First, list every parent model a comment can attach to in an enum marked #[morph], where each variant holds one model:

1// src/models/comment.rs
2use laravel::model::{MorphTo, MorphType, model, morph};
3use laravel::time::Timestamp;
4 
5use crate::models::{Post, Video};
6 
7#[morph]
8pub enum Commentable {
9 Post(Post),
10 Video(Video),
11}
12 
13#[model]
14pub struct Comment {
15 pub id: i64,
16 pub body: String,
17 pub commentable_type: MorphType<Commentable>,
18 pub commentable_id: i64,
19 pub created_at: Timestamp,
20 pub updated_at: Timestamp,
21 
22 #[morph_to]
23 pub commentable: MorphTo<Commentable>,
24}
1// src/models/comment.rs
2use laravel::model::{MorphTo, MorphType, model, morph};
3use laravel::time::Timestamp;
4 
5use crate::models::{Post, Video};
6 
7#[morph]
8pub enum Commentable {
9 Post(Post),
10 Video(Video),
11}
12 
13#[model]
14pub struct Comment {
15 pub id: i64,
16 pub body: String,
17 pub commentable_type: MorphType<Commentable>,
18 pub commentable_id: i64,
19 pub created_at: Timestamp,
20 pub updated_at: Timestamp,
21 
22 #[morph_to]
23 pub commentable: MorphTo<Commentable>,
24}

A #[morph_to] field reads the two columns named after it (commentable_type and commentable_id). If the parent is optional, wrap both columns and the relationship (MorphTo<Option<Commentable>>) in Option.

The type column stores each model's morph name, defaulting to the struct's snake-case name (post for Post, blog_post for BlogPost). To customize the stored name (for example, to preserve existing values in the database), annotate the model with #[model(morph = "..")]:

1#[model(morph = "clip")]
2pub struct Video {
3 // ...
4}
1#[model(morph = "clip")]
2pub struct Video {
3 // ...
4}

The #[morph] enum defines the complete set of allowed parents: MorphType<Commentable> only decodes and writes names listed in the enum (post and clip), and all models in the enum must share the same primary key type and distinct morph names. If you later rename a model struct, keep its original database identifier with #[model(morph = "..")].

Next, declare the inverse relationship on each parent model by pointing #[morph_many] or #[morph_one] at the child's #[morph_to] descriptor (typos or unlisted parents fail at compile time):

1// src/models/post.rs
2use laravel::model::{MorphMany, MorphOne, model};
3 
4use crate::models::{Comment, Image};
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 pub title: String,
10 
11 #[morph_many(Comment::commentable)]
12 pub comments: MorphMany<Comment>,
13 #[morph_one(Image::imageable)]
14 pub image: MorphOne<Option<Image>>,
15}
1// src/models/post.rs
2use laravel::model::{MorphMany, MorphOne, model};
3 
4use crate::models::{Comment, Image};
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 pub title: String,
10 
11 #[morph_many(Comment::commentable)]
12 pub comments: MorphMany<Comment>,
13 #[morph_one(Image::imageable)]
14 pub image: MorphOne<Option<Image>>,
15}

#[morph_many] and #[morph_one] mirror #[has_many] and #[has_one], filtering by the parent's morph type automatically so a video's comments never appear under a post sharing the same ID:

1let post = Post::query()
2 .with((Post::comments, Post::image))
3 .find_or_fail(id)
4 .await?;
5 
6let recent = post
7 .comments()
8 .order_by(Comment::created_at.desc())
9 .limit(10)
10 .get()
11 .await?;
1let post = Post::query()
2 .with((Post::comments, Post::image))
3 .find_or_fail(id)
4 .await?;
5 
6let recent = post
7 .comments()
8 .order_by(Comment::created_at.desc())
9 .limit(10)
10 .get()
11 .await?;

If the parent key uses a non-default column name, pass local_key:

1#[morph_many(Comment::commentable, local_key = "uuid")]
2pub comments: MorphMany<Comment>,
1#[morph_many(Comment::commentable, local_key = "uuid")]
2pub comments: MorphMany<Comment>,

On #[morph_one], you may also use latest_of_many and the other of_many options to pick a single standout record:

1#[morph_one(Image::imageable, latest_of_many)]
2pub latest_image: MorphOne<Option<Image>>,
1#[morph_one(Image::imageable, latest_of_many)]
2pub latest_image: MorphOne<Option<Image>>,

Loading polymorphic relationships

Load a #[morph_to] relationship with with as you would a #[belongs_to]. The loaded field dereferences to the morph enum, so you can match on it to handle each parent type:

1use crate::models::{Comment, Commentable};
2 
3pub async fn index() -> laravel::Result<Page> {
4 let comments = Comment::query()
5 .with(Comment::commentable)
6 .order_by(Comment::created_at.desc())
7 .limit(50)
8 .get()
9 .await?;
10 
11 for comment in &comments {
12 let title = match &*comment.commentable {
13 Commentable::Post(post) => post.title.as_str(),
14 Commentable::Video(video) => video.name.as_str(),
15 };
16 }
17 
18 Ok(inertia::render("Comments/Index", props! { comments }))
19}
1use crate::models::{Comment, Commentable};
2 
3pub async fn index() -> laravel::Result<Page> {
4 let comments = Comment::query()
5 .with(Comment::commentable)
6 .order_by(Comment::created_at.desc())
7 .limit(50)
8 .get()
9 .await?;
10 
11 for comment in &comments {
12 let title = match &*comment.commentable {
13 Commentable::Post(post) => post.title.as_str(),
14 Commentable::Video(video) => video.name.as_str(),
15 };
16 }
17 
18 Ok(inertia::render("Comments/Index", props! { comments }))
19}

Loading a non-optional MorphTo<Commentable> fails if a comment points to a deleted parent; use MorphTo<Option<Commentable>> if orphaned records are possible.

To eager-load nested relationships specific to each parent variant, chain morph_with for each target model (relationships belonging to models outside the morph enum fail to compile). The example below loads every comment along with its parent, eager-loading the user relationship for posts and the channel and tags relationships for videos:

1let comments = Comment::query()
2 .with(
3 Comment::commentable
4 .morph_with(Post::user)
5 .morph_with((Video::channel, Video::tags)),
6 )
7 .get()
8 .await?;
1let comments = Comment::query()
2 .with(
3 Comment::commentable
4 .morph_with(Post::user)
5 .morph_with((Video::channel, Video::tags)),
6 )
7 .get()
8 .await?;

You may also customize the query for a specific parent type using query::<T>:

1let comments = Comment::query()
2 .with(
3 Comment::commentable.query::<Post>(|posts| {
4 posts.with(Post::user).with_count(Post::comments)
5 }),
6 )
7 .get()
8 .await?;
1let comments = Comment::query()
2 .with(
3 Comment::commentable.query::<Post>(|posts| {
4 posts.with(Post::user).with_count(Post::comments)
5 }),
6 )
7 .get()
8 .await?;

load and load_missing accept the same descriptors when eager-loading onto models you have already retrieved, and comment.commentable().first() fetches a single comment's parent on demand:

1// Eager-load missing parents (and each post's author) onto an existing collection...
2comments
3 .load_missing(Comment::commentable.morph_with(Post::user))
4 .await?;
5 
6// Fetch a single comment's parent on demand...
7match comment.commentable().first().await? {
8 Some(Commentable::Post(post)) => {
9 // ...
10 }
11 Some(Commentable::Video(video)) => {
12 // ...
13 }
14 None => {
15 // The parent was deleted or the morph columns are null...
16 }
17}
1// Eager-load missing parents (and each post's author) onto an existing collection...
2comments
3 .load_missing(Comment::commentable.morph_with(Post::user))
4 .await?;
5 
6// Fetch a single comment's parent on demand...
7match comment.commentable().first().await? {
8 Some(Commentable::Post(post)) => {
9 // ...
10 }
11 Some(Commentable::Video(video)) => {
12 // ...
13 }
14 None => {
15 // The parent was deleted or the morph columns are null...
16 }
17}

Because #[morph_to] points to one record, passing it to with_count fails to compile; use has instead.

Filtering by the model a relationship refers to

has(Comment::commentable) matches comments whose parent exists, while doesnt_have matches comments whose parent is missing. To filter on a specific parent type's columns, narrow the relationship with of::<Post>(). Both has_where and doesnt_have_where restrict the query to comments belonging to that parent type (comments on videos are excluded):

1// Comments on posts whose title mentions Rust...
2let about_rust = Comment::query()
3 .has_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))
4 .get()
5 .await?;
6 
7// Comments on posts whose title does not mention Rust...
8let other_posts = Comment::query()
9 .doesnt_have_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))
10 .get()
11 .await?;
1// Comments on posts whose title mentions Rust...
2let about_rust = Comment::query()
3 .has_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))
4 .get()
5 .await?;
6 
7// Comments on posts whose title does not mention Rust...
8let other_posts = Comment::query()
9 .doesnt_have_where(Comment::commentable.of::<Post>(), Post::title.contains("Rust"))
10 .get()
11 .await?;

To match across multiple parent types in one query, combine exists_where conditions with |. The example below retrieves every comment that belongs either to a post whose title contains "Rust" or to a video whose name contains "Rust":

1let about_rust = Comment::query()
2 .filter(
3 Comment::commentable.of::<Post>().exists_where(Post::title.contains("Rust"))
4 | Comment::commentable.of::<Video>().exists_where(Video::name.contains("Rust")),
5 )
6 .get()
7 .await?;
1let about_rust = Comment::query()
2 .filter(
3 Comment::commentable.of::<Post>().exists_where(Post::title.contains("Rust"))
4 | Comment::commentable.of::<Video>().exists_where(Video::name.contains("Rust")),
5 )
6 .get()
7 .await?;

To filter comments belonging to a specific model instance, use is(&post). It matches both commentable_type and commentable_id, preventing collisions with a video sharing the same ID:

1let comments = Comment::query().filter(Comment::commentable.is(&post)).get().await?;
1let comments = Comment::query().filter(Comment::commentable.is(&post)).get().await?;

Calling post.comments() queries the same rows from the parent side.

To filter solely by parent type without a model instance, compare the type column against MorphType::of:

1// Comments belonging to videos...
2let video_comments = Comment::query()
3 .filter(Comment::commentable_type.eq(MorphType::of::<Video>()))
4 .get()
5 .await?;
6 
7// Comments belonging to any parent type except posts...
8let non_post_comments = Comment::query()
9 .filter(Comment::commentable_type.ne(MorphType::of::<Post>()))
10 .get()
11 .await?;
1// Comments belonging to videos...
2let video_comments = Comment::query()
3 .filter(Comment::commentable_type.eq(MorphType::of::<Video>()))
4 .get()
5 .await?;
6 
7// Comments belonging to any parent type except posts...
8let non_post_comments = Comment::query()
9 .filter(Comment::commentable_type.ne(MorphType::of::<Post>()))
10 .get()
11 .await?;

Writing polymorphic relationships

Creating a comment through its parent's relationship populates both the type and ID columns automatically:

1use laravel::model::create;
2 
3let comment = create!(post.comments() { body: "Great post!" }).await?;
1use laravel::model::create;
2 
3let comment = create!(post.comments() { body: "Great post!" }).await?;

You may also assign any model in the morph enum directly to the #[morph_to] field in create! or update!:

1use laravel::model::{create, update};
2 
3let mut comment = create!(Comment { body: "Great video!", commentable: &video }).await?;
4 
5update!(comment { commentable: &post }).await?;
1use laravel::model::{create, update};
2 
3let mut comment = create!(Comment { body: "Great video!", commentable: &video }).await?;
4 
5update!(comment { commentable: &post }).await?;

Laravel hydrates comment.commentable with the assigned model immediately, so reading it requires no extra query.

Nested creation works like #[has_many]: creating a post with inline comments populates post.comments as well as each comment's commentable field:

1let post = create!(Post {
2 title: "Hello",
3 user: &user,
4 comments: [Comment { body: "First!" }, Comment { body: "Second!" }],
5})
6.await?;
1let post = create!(Post {
2 title: "Hello",
3 user: &user,
4 comments: [Comment { body: "First!" }, Comment { body: "Second!" }],
5})
6.await?;

The Post inside each comment's commentable field does not carry its own loaded relationships, so post.comments is unloaded there. Factory has calls hydrate commentable as well, whereas post.comments().create() returns only the comment's columns until you load Comment::commentable.

You may also pass a create! builder or a factory to a #[morph_to] field, inserting the parent first inside the same transaction:

1// Insert a new video and comment together in one transaction...
2let comment = create!(Comment {
3 body: "First!",
4 commentable: create!(Video { name: "Premiere" }),
5})
6.await?;
7 
8// Or default a comment factory's parent to a new post...
9#[factory(Comment)]
10pub struct CommentFactory;
11 
12impl CommentFactory {
13 fn definition(fake: &mut Faker) -> impl IntoCreate<Comment> {
14 create!(Comment {
15 body: fake.sentence(),
16 commentable: Post::factory(),
17 })
18 }
19}
1// Insert a new video and comment together in one transaction...
2let comment = create!(Comment {
3 body: "First!",
4 commentable: create!(Video { name: "Premiere" }),
5})
6.await?;
7 
8// Or default a comment factory's parent to a new post...
9#[factory(Comment)]
10pub struct CommentFactory;
11 
12impl CommentFactory {
13 fn definition(fake: &mut Faker) -> impl IntoCreate<Comment> {
14 create!(Comment {
15 body: fake.sentence(),
16 commentable: Post::factory(),
17 })
18 }
19}

Many-to-many polymorphic relationships

Tags are a classic example of a polymorphic many-to-many relationship: posts and videos can share tags, and each tag can be applied to many posts and videos. One taggables join table stores every link, using morphs("taggable") to create the two polymorphic columns (taggable_type and taggable_id) alongside tag_id:

1tx.schema()
2 .create("taggables", |table| {
3 table.foreign_id("tag_id");
4 table.morphs("taggable");
5 table.timestamps();
6 })
7 .await?;
1tx.schema()
2 .create("taggables", |table| {
3 table.foreign_id("tag_id");
4 table.morphs("taggable");
5 table.timestamps();
6 })
7 .await?;

Because a join table has no standalone model for #[morph_to], its join row holds a MorphKey<Taggable> field that bundles the taggable_type and taggable_id columns into a single (type, id) pair:

1// src/models/tag.rs
2use laravel::model::{MorphKey, MorphedByMany, join_row, model, morph};
3use laravel::time::Timestamp;
4 
5use crate::models::{Post, Video};
6 
7#[morph]
8pub enum Taggable {
9 Post(Post),
10 Video(Video),
11}
12 
13#[join_row(table = "taggables")]
14pub struct Tagging {
15 pub taggable: MorphKey<Taggable>,
16 pub created_at: Timestamp,
17 pub updated_at: Timestamp,
18}
19 
20#[model]
21pub struct Tag {
22 pub id: i64,
23 pub name: String,
24 
25 #[morphed_by_many(Tagging::taggable)]
26 pub posts: MorphedByMany<Post>,
27 #[morphed_by_many(Tagging::taggable)]
28 pub videos: MorphedByMany<Video>,
29}
1// src/models/tag.rs
2use laravel::model::{MorphKey, MorphedByMany, join_row, model, morph};
3use laravel::time::Timestamp;
4 
5use crate::models::{Post, Video};
6 
7#[morph]
8pub enum Taggable {
9 Post(Post),
10 Video(Video),
11}
12 
13#[join_row(table = "taggables")]
14pub struct Tagging {
15 pub taggable: MorphKey<Taggable>,
16 pub created_at: Timestamp,
17 pub updated_at: Timestamp,
18}
19 
20#[model]
21pub struct Tag {
22 pub id: i64,
23 pub name: String,
24 
25 #[morphed_by_many(Tagging::taggable)]
26 pub posts: MorphedByMany<Post>,
27 #[morphed_by_many(Tagging::taggable)]
28 pub videos: MorphedByMany<Video>,
29}

On each taggable model, declare #[morph_to_many] pointing at the same MorphKey field:

1// src/models/post.rs
2use laravel::model::{MorphToMany, model};
3 
4use crate::models::{Tag, Tagging};
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 pub title: String,
10 
11 #[morph_to_many(Tagging::taggable)]
12 pub tags: MorphToMany<Tag, Tagging>,
13}
1// src/models/post.rs
2use laravel::model::{MorphToMany, model};
3 
4use crate::models::{Tag, Tagging};
5 
6#[model]
7pub struct Post {
8 pub id: i64,
9 pub title: String,
10 
11 #[morph_to_many(Tagging::taggable)]
12 pub tags: MorphToMany<Tag, Tagging>,
13}

The relationship inherits the join table name from Tagging and expects the related key column to be tag_id (override it with related_join_key on #[morph_to_many] or foreign_join_key on #[morphed_by_many]). On Tag, declare one #[morphed_by_many] field per taggable model type.

Polymorphic many-to-many relationships support the same query and write methods as #[belongs_to_many], automatically scoping every query and write by taggable_type so syncing a video's tags never touches a post's tags:

1use laravel::model::create;
2 
3post.tags().sync([rust.id, laravel.id]).await?;
4video.tags().attach(&rust).await?;
5 
6let tag = create!(post.tags() { name: "Tutorial" }).await?;
1use laravel::model::create;
2 
3post.tags().sync([rust.id, laravel.id]).await?;
4video.tags().attach(&rust).await?;
5 
6let tag = create!(post.tags() { name: "Tutorial" }).await?;

Because Post::tags includes Tagging in its field type (MorphToMany<Tag, Tagging>), each loaded tag exposes its join-table row on .join, where you can read timestamps, any extra join columns, or the morph pair through morph() and key():

1let post = Post::query().with(Post::tags).find_or_fail(1).await?;
2 
3for tag in &post.tags {
4 let name = &tag.name;
5 let tagged_at = tag.join.created_at;
6 let morph = tag.join.taggable.morph(); // MorphType<Taggable> ("post")
7 let id = tag.join.taggable.key(); // &i64 (1)
8}
1let post = Post::query().with(Post::tags).find_or_fail(1).await?;
2 
3for tag in &post.tags {
4 let name = &tag.name;
5 let tagged_at = tag.join.created_at;
6 let morph = tag.join.taggable.morph(); // MorphType<Taggable> ("post")
7 let id = tag.join.taggable.key(); // &i64 (1)
8}

If you do not need to read join-table columns when iterating over tags, you may leave Tagging out of the field type and write MorphToMany<Tag> (or MorphedByMany<Post> on Tag):

1#[model]
2pub struct Video {
3 pub id: i64,
4 pub name: String,
5 
6 #[morph_to_many(Tagging::taggable)]
7 pub tags: MorphToMany<Tag>,
8}
1#[model]
2pub struct Video {
3 pub id: i64,
4 pub name: String,
5 
6 #[morph_to_many(Tagging::taggable)]
7 pub tags: MorphToMany<Tag>,
8}

With MorphToMany<Tag>, iterating &video.tags yields plain Tag models without .join. Because the #[morph_to_many(Tagging::taggable)] attribute still points to Tagging, Laravel continues to populate join-table timestamps automatically and still accepts joined! values when writing extra columns.

Serializing relationships

When a model is serialized to JSON (for example, in a Json response or Inertia props), loaded relationships appear under their field names, while unloaded relationships are omitted automatically so responses only contain data you explicitly loaded:

1use laravel::prelude::*;
2 
3use crate::models::User;
4 
5pub async fn show(mut user: User) -> laravel::Result<Json<User>> {
6 user.load(User::posts).await?;
7 
8 Ok(Json(user))
9}
1use laravel::prelude::*;
2 
3use crate::models::User;
4 
5pub async fn show(mut user: User) -> laravel::Result<Json<User>> {
6 user.load(User::posts).await?;
7 
8 Ok(Json(user))
9}

That handler returns a JSON response containing the user along with its loaded posts array:

1{
2 "id": 1,
3 "name": "Taylor",
4 "posts": [
5 {
6 "id": 1,
7 "user_id": 1,
8 "title": "Hello"
9 }
10 ]
11}
1{
2 "id": 1,
3 "name": "Taylor",
4 "posts": [
5 {
6 "id": 1,
7 "user_id": 1,
8 "title": "Hello"
9 }
10 ]
11}

Related models follow the same serialization rules as top-level models, so any fields marked #[serde(skip)] or #[serde(skip_serializing)] on a related model are also omitted from the response. If a model specifies #[serde(rename_all = "camelCase")], relationship and aggregate keys follow the same casing rule (for example, blogPosts, blogPostsCount, and blogPostsSumVotes).

Serializing aggregates

Loaded relationship aggregates appear alongside the model's columns with suffixes such as _count, _exists, _sum_<column>, and _max_<column> (for example, posts_count, posts_sum_votes, and posts_max_published_at):

1let user = User::query()
2 .with_count(User::posts)
3 .find_or_fail(1)
4 .await?;
1let user = User::query()
2 .with_count(User::posts)
3 .find_or_fail(1)
4 .await?;
1{
2 "id": 1,
3 "name": "Taylor",
4 "posts_count": 1
5}
1{
2 "id": 1,
3 "name": "Taylor",
4 "posts_count": 1
5}

Omitting loaded relationships

To serialize a model without any loaded relationships or aggregates, call without_relations(), which returns a copy containing only the model's columns:

1Ok(Json(user.without_relations()))
1Ok(Json(user.without_relations()))
1{
2 "id": 1,
3 "name": "Taylor"
4}
1{
2 "id": 1,
3 "name": "Taylor"
4}

Serializing join rows

When a relationship includes a join row, each related model serializes with its join attributes nested under join:

1{
2 "id": 1,
3 "name": "Taylor",
4 "roles": [
5 {
6 "id": 2,
7 "name": "admin",
8 "join": {
9 "level": "owner",
10 "expires_at": null,
11 "created_at": "2026-11-10T09:00:00Z",
12 "updated_at": "2026-11-10T09:00:00Z"
13 }
14 }
15 ]
16}
1{
2 "id": 1,
3 "name": "Taylor",
4 "roles": [
5 {
6 "id": 2,
7 "name": "admin",
8 "join": {
9 "level": "owner",
10 "expires_at": null,
11 "created_at": "2026-11-10T09:00:00Z",
12 "updated_at": "2026-11-10T09:00:00Z"
13 }
14 }
15 ]
16}

Serializing polymorphic relationships

A loaded #[morph_to] relationship serializes directly as its underlying model without an enum wrapper tag; the type column (commentable_type) indicates which model the nested object represents:

1use laravel::prelude::*;
2 
3use crate::models::Comment;
4 
5pub async fn show(mut comment: Comment) -> laravel::Result<Json<Comment>> {
6 comment.load(Comment::commentable).await?;
7 
8 Ok(Json(comment))
9}
1use laravel::prelude::*;
2 
3use crate::models::Comment;
4 
5pub async fn show(mut comment: Comment) -> laravel::Result<Json<Comment>> {
6 comment.load(Comment::commentable).await?;
7 
8 Ok(Json(comment))
9}

For a comment belonging to a Video, that handler returns:

1{
2 "id": 4,
3 "body": "Great video!",
4 "commentable_type": "video",
5 "commentable_id": 1,
6 "commentable": {
7 "id": 1,
8 "name": "Intro"
9 }
10}
1{
2 "id": 4,
3 "body": "Great video!",
4 "commentable_type": "video",
5 "commentable_id": 1,
6 "commentable": {
7 "id": 1,
8 "name": "Intro"
9 }
10}

For a polymorphic many-to-many relationship that includes a join row (such as MorphToMany<Tag, Tagging>), the join row's MorphKey field serializes as an object containing type and id:

1pub async fn show(mut post: Post) -> laravel::Result<Json<Post>> {
2 post.load(Post::tags).await?;
3 
4 Ok(Json(post))
5}
1pub async fn show(mut post: Post) -> laravel::Result<Json<Post>> {
2 post.load(Post::tags).await?;
3 
4 Ok(Json(post))
5}
1{
2 "id": 1,
3 "title": "Hello",
4 "tags": [
5 {
6 "id": 1,
7 "name": "Rust",
8 "join": {
9 "taggable": {
10 "type": "post",
11 "id": 1
12 },
13 "created_at": "2026-11-10T09:00:00Z",
14 "updated_at": "2026-11-10T09:00:00Z"
15 }
16 }
17 ]
18}
1{
2 "id": 1,
3 "title": "Hello",
4 "tags": [
5 {
6 "id": 1,
7 "name": "Rust",
8 "join": {
9 "taggable": {
10 "type": "post",
11 "id": 1
12 },
13 "created_at": "2026-11-10T09:00:00Z",
14 "updated_at": "2026-11-10T09:00:00Z"
15 }
16 }
17 ]
18}