Skip to content

Getting Started

Models

Database: Models

Introduction

Laravel includes a built-in object-relational mapper (ORM) for working with your database using typed Rust structs. Each database table has a corresponding model that lets you query, insert, update, and delete records while checking column names, relationships, and types at compile time.

A model is a Rust struct annotated with #[model], where each field maps to a column and each instance represents a row. Models build on the same query builder used for raw tables, and use the create! and update! macros to write changes safely.

Before getting started, configure a database connection and create the model's table with a migration. Models live in src/models/, one file per model, alongside the included User model:

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

#[default] marks a column that has a database default (such as votes and views), allowing you to omit those fields in create! and receive the database-assigned value back. The user field is not a database column; it defines a relationship to the user who authored the post.

You can query a model directly from a route handler:

1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn index() -> laravel::Result<Page> {
6 let posts = Post::query()
7 .filter(Post::votes.gt(100) & Post::published_at.is_not_null())
8 .order_by(Post::published_at.desc())
9 .get()
10 .await?;
11 
12 Ok(inertia::render("Posts/Index", props! { posts }))
13}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn index() -> laravel::Result<Page> {
6 let posts = Post::query()
7 .filter(Post::votes.gt(100) & Post::published_at.is_not_null())
8 .order_by(Post::published_at.desc())
9 .get()
10 .await?;
11 
12 Ok(inertia::render("Posts/Index", props! { posts }))
13}

Post::votes and Post::published_at are typed columns. Because each column carries its Rust type, comparing Post::votes against a string fails at compile time rather than failing at runtime.

Declaring models

Apply #[model] to a struct with named fields. Each field's Rust type determines how its column is read and written, and nullable columns are wrapped in Option<T>.

The #[model] macro derives Clone, Debug, and Serialize automatically, so you do not need to derive them yourself. To control which fields appear in JSON and Inertia responses, check out Serializing models.

Table and column names

Laravel infers table, primary key, and column names by convention, so most models require no overrides:

Convention Rule Override
Connection The default connection #[model(connection = "directory")]
Table The struct's name in snake case, made plural: BlogPost is blog_posts, and Category is categories #[model(table = "people")]
Key The id field #[key] on another field
Column The field's name #[column("is_admin")] on the field
Route key The key #[model(route_key = "slug")]
1use laravel::model::model;
2use laravel::str::Uuid;
3 
4#[model(table = "people", connection = "directory", route_key = "slug")]
5pub struct Person {
6 #[key]
7 pub uuid: Uuid,
8 pub slug: String,
9 #[column("is_admin")]
10 pub admin: bool,
11}
1use laravel::model::model;
2use laravel::str::Uuid;
3 
4#[model(table = "people", connection = "directory", route_key = "slug")]
5pub struct Person {
6 #[key]
7 pub uuid: Uuid,
8 pub slug: String,
9 #[column("is_admin")]
10 pub admin: bool,
11}

#[model] generates associated functions and methods such as query, find, create, update, and delete, so a struct field cannot reuse those names. If a table has a column named query, name the Rust field something else and annotate it with #[column("query")].

Primary keys

Laravel determines how new primary keys are generated from the key field's type. Most tables use an auto-incrementing i64 key assigned by the database:

Key type New keys
i64, i32, and the other integer types Assigned by the database, such as with the auto-incrementing column created by table.id()
Uuid create generates a time-ordered version 7 UUID
Ulid create generates a ULID
String Must be provided explicitly when creating the model

Defining fields

Each field on a model struct corresponds to a column in its database table. Wrap nullable columns in Option<T>, and annotate columns that have a database default value with #[default] so you can omit them when creating records.

For example, an Invoice model might combine numbers, exact decimals, calendar dates, IP addresses, and timestamps:

1use std::net::IpAddr;
2 
3use laravel::model::model;
4use laravel::numeric::Decimal;
5use laravel::str::Uuid;
6use laravel::time::{Timestamp, civil::Date};
7 
8#[model]
9pub struct Invoice {
10 pub id: Uuid,
11 pub number: String,
12 pub subtotal: Decimal,
13 #[default]
14 pub paid: bool,
15 pub due_on: Option<Date>,
16 pub billed_from: Option<IpAddr>,
17 pub created_at: Timestamp,
18 pub updated_at: Timestamp,
19}
1use std::net::IpAddr;
2 
3use laravel::model::model;
4use laravel::numeric::Decimal;
5use laravel::str::Uuid;
6use laravel::time::{Timestamp, civil::Date};
7 
8#[model]
9pub struct Invoice {
10 pub id: Uuid,
11 pub number: String,
12 pub subtotal: Decimal,
13 #[default]
14 pub paid: bool,
15 pub due_on: Option<Date>,
16 pub billed_from: Option<IpAddr>,
17 pub created_at: Timestamp,
18 pub updated_at: Timestamp,
19}

Laravel supports the following field types out of the box (any of them may be wrapped in Option<T> for nullable columns):

Rust type Import Column kind
i8, i16, i32, i64 Prelude Signed integers
u8, u16, u32, u64, usize Prelude Unsigned integers
f32, f64 Prelude Floating-point numbers
Decimal laravel::numeric::Decimal Exact decimals (money, rates)
bool Prelude Booleans
String Prelude Text / VARCHAR
Vec<u8> Prelude Binary / BLOB / BYTEA
Timestamp laravel::time::Timestamp Timestamps (TIMESTAMPTZ / TIMESTAMP)
civil::Date, civil::Time, civil::DateTime laravel::time::civil Calendar dates, times, and datetimes
Uuid, Ulid laravel::str UUIDs and ULIDs
IpAddr, Ipv4Addr, Ipv6Addr std::net IP addresses
Json<T>, serde_json::Value, #[derive(db::Json)] laravel::db JSON columns
#[derive(Enum)] Prelude Enum columns
Vector laravel::db::Vector Vector embeddings (pgvector / MariaDB)
Encrypted<T> laravel::crypt::Encrypted Encrypted columns
PasswordHash laravel::hash::PasswordHash Hashed passwords
RememberToken laravel::auth::RememberToken Authentication remember tokens

Timestamps

If your model defines created_at and updated_at fields (as Timestamp or Option<Timestamp> to match table.timestamps()), Laravel populates both automatically on create! and refreshes updated_at on every update. If you explicitly pass a timestamp during a create or update, Laravel preserves your value, which is useful when importing historical records. Laravel truncates model timestamps to the connection's time precision so they match what the database stores.

Model query methods (update, increment, and decrement) also maintain updated_at. Bulk insert calls and raw db::table queries do not set timestamps automatically, so supply them explicitly when needed.

Enum columns

To store a Rust enum in a text column, derive Enum alongside Clone, Debug, Serialize, and Deserialize. Laravel stores each variant using its Serde name (such as "pro" with #[serde(rename_all = "snake_case")]):

1// src/models/customer.rs
2use laravel::prelude::*;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]
7#[serde(rename_all = "snake_case")]
8pub enum Plan {
9 Free,
10 Pro,
11}
12 
13#[model]
14pub struct Customer {
15 pub id: i64,
16 pub email: String,
17 pub plan: Plan,
18}
1// src/models/customer.rs
2use laravel::prelude::*;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]
7#[serde(rename_all = "snake_case")]
8pub enum Plan {
9 Free,
10 Pro,
11}
12 
13#[model]
14pub struct Customer {
15 pub id: i64,
16 pub email: String,
17 pub plan: Plan,
18}

Enum columns work with typed queries and writes, such as Customer::plan.eq(Plan::Pro) and update!(customer { plan: Plan::Pro }). To store an enum whose variants carry data, derive db::Json and store it in a JSON column instead.

JSON columns

When a column stores structured JSON data, such as user preferences or integration settings, define a Rust struct for the shape and derive db::Json alongside Clone, Debug, Serialize, and Deserialize. Back the column with table.json(..) or table.jsonb(..) in your migration:

1// src/models/user.rs
2use laravel::db;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Json)]
7pub struct Preferences {
8 pub theme: String,
9 pub notifications: bool,
10}
11 
12#[model]
13pub struct User {
14 pub id: i64,
15 pub email: String,
16 pub preferences: Preferences,
17}
1// src/models/user.rs
2use laravel::db;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Json)]
7pub struct Preferences {
8 pub theme: String,
9 pub notifications: bool,
10}
11 
12#[model]
13pub struct User {
14 pub id: i64,
15 pub email: String,
16 pub preferences: Preferences,
17}

If you don't need a dedicated struct, fields may also use Json<Vec<T>>, Json<HashMap<K, V>>, or serde_json::Value.

When creating a model with a db::Json field, pass a variable or wrap an inline struct literal in parentheses inside create! so it isn't parsed as a nested related model:

1use laravel::model::create;
2 
3let preferences = Preferences {
4 theme: "light".into(),
5 notifications: true,
6};
7 
8let mut user = create!(User { email: "[email protected]", preferences }).await?;
1use laravel::model::create;
2 
3let preferences = Preferences {
4 theme: "light".into(),
5 notifications: true,
6};
7 
8let mut user = create!(User { email: "[email protected]", preferences }).await?;

To replace the whole JSON value, pass the updated struct to update!:

1use laravel::model::update;
2 
3let mut preferences = user.preferences.clone();
4preferences.theme = "dark".into();
5 
6update!(user { preferences }).await?;
1use laravel::model::update;
2 
3let mut preferences = user.preferences.clone();
4preferences.theme = "dark".into();
5 
6update!(user { preferences }).await?;

To update a single nested key in place without replacing the entire JSON document, call update_values with db::values! and arrow notation (column->key). Calling update_values on a model writes the change in SQL and reloads the model in place, while calling it on a query updates all matching rows in a single statement:

1use laravel::db::values;
2 
3user.update_values(values! { "preferences->theme": "dark" }).await?;
4 
5User::query()
6 .filter(User::id.eq(user.id))
7 .update_values(values! { "preferences->notifications": false })
8 .await?;
1use laravel::db::values;
2 
3user.update_values(values! { "preferences->theme": "dark" }).await?;
4 
5User::query()
6 .filter(User::id.eq(user.id))
7 .update_values(values! { "preferences->notifications": false })
8 .await?;

You can also filter models by JSON keys directly on the typed column with path, separating nested keys with -> and indexing arrays with [n], or check JSON array membership and length with json_contains and json_length:

1let dark_mode_users = User::query()
2 .filter(User::preferences.path("theme").eq("dark"))
3 .get()
4 .await?;
5 
6let email_subscribers = User::query()
7 .filter(User::preferences.path("notifications->email").eq(true))
8 .filter(User::preferences.path("languages[0]").eq("en"))
9 .get()
10 .await?;
1let dark_mode_users = User::query()
2 .filter(User::preferences.path("theme").eq("dark"))
3 .get()
4 .await?;
5 
6let email_subscribers = User::query()
7 .filter(User::preferences.path("notifications->email").eq(true))
8 .filter(User::preferences.path("languages[0]").eq("en"))
9 .get()
10 .await?;

To learn more about JSON path expressions, json_contains, and json_length, check out the query builder's JSON columns section.

Values over several columns

When a value spans multiple columns, such as a price with an amount and currency that you want to sum and index separately, derive db::Embed on a struct holding those columns and mark the model field #[embed]:

1// src/models/order.rs
2use laravel::db;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Embed)]
7pub struct Money {
8 pub amount: i64,
9 pub currency: String,
10}
11 
12#[model]
13pub struct Order {
14 pub id: i64,
15 #[embed]
16 pub total: Money,
17 #[embed(prefix = "refunded")]
18 pub refunded: Money,
19}
1// src/models/order.rs
2use laravel::db;
3use laravel::model::model;
4use serde::{Deserialize, Serialize};
5 
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Embed)]
7pub struct Money {
8 pub amount: i64,
9 pub currency: String,
10}
11 
12#[model]
13pub struct Order {
14 pub id: i64,
15 #[embed]
16 pub total: Money,
17 #[embed(prefix = "refunded")]
18 pub refunded: Money,
19}

By default, Laravel prefixes each embedded column with the model's field name, so total maps to total_amount and total_currency, and refunded maps to refunded_amount and refunded_currency. Pass #[embed(prefix = "")] to use the embedded struct's field names without a prefix. The embedded struct should derive Clone, Debug, Serialize, and Deserialize alongside db::Embed, and each of its fields must be a valid column type.

Passing a single Money value populates all of its underlying columns across create!, update!, fill structs, and query updates. Wrap a struct literal in parentheses inside create! so it is not parsed as a nested related model:

1use laravel::model::{create, update};
2 
3let usd = |amount| Money { amount, currency: "USD".into() };
4 
5let mut order = create!(Order {
6 total: usd(1500),
7 refunded: (Money { amount: 0, currency: "USD".into() }),
8})
9.await?;
10 
11update!(order { refunded: usd(500) }).await?;
1use laravel::model::{create, update};
2 
3let usd = |amount| Money { amount, currency: "USD".into() };
4 
5let mut order = create!(Order {
6 total: usd(1500),
7 refunded: (Money { amount: 0, currency: "USD".into() }),
8})
9.await?;
10 
11update!(order { refunded: usd(500) }).await?;

Order::total exposes a typed column for each embedded field, allowing you to filter or pluck individual sub-columns, or compare the entire embedded value at once with eq and ne:

1let large_orders = Order::query()
2 .filter(Order::total.amount.gt(1000))
3 .get()
4 .await?;
5 
6let currencies = Order::query()
7 .pluck(Order::total.currency)
8 .await?;
9 
10let price = Money { amount: 1500, currency: "USD".into() };
11 
12let matching = Order::query().filter(Order::total.eq(&price)).get().await?;
13let others = Order::query().filter(Order::total.ne(&price)).get().await?;
1let large_orders = Order::query()
2 .filter(Order::total.amount.gt(1000))
3 .get()
4 .await?;
5 
6let currencies = Order::query()
7 .pluck(Order::total.currency)
8 .await?;
9 
10let price = Money { amount: 1500, currency: "USD".into() };
11 
12let matching = Order::query().filter(Order::total.eq(&price)).get().await?;
13let others = Order::query().filter(Order::total.ne(&price)).get().await?;

Updates only write the sub-columns that actually changed, and JSON serialization represents the field as a nested object (such as "total": { "amount": 1500, "currency": "USD" }).

Retrieving models

Once you have declared a model and migrated its table, you can retrieve all records from the table using all:

1use crate::models::Post;
2 
3let posts = Post::all().await?;
1use crate::models::Post;
2 
3let posts = Post::all().await?;

For filtering, ordering, limits, or pagination, begin a query with Post::query(), which wraps the query builder for the model's table, and finish it with get:

1let posts = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .order_by(Post::published_at.desc())
4 .limit(10)
5 .get()
6 .await?;
1let posts = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .order_by(Post::published_at.desc())
4 .limit(10)
5 .get()
6 .await?;

To retrieve a single model by its primary key, call find, which returns Option<Post>:

1let post: Option<Post> = Post::find(1).await?;
1let post: Option<Post> = Post::find(1).await?;

If you'd rather fail with a 404 response when no matching row exists, use find_or_fail. It returns a ModelNotFound error that Laravel automatically converts into a 404 response (rendering No query results for model `Post` with the key `1`. for JSON clients or a 404 error page for browsers):

1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Post>> {
6 // Returns a 404 response automatically if no post has this ID...
7 let post = Post::find_or_fail(id).await?;
8 
9 Ok(Json(post))
10}
1use laravel::prelude::*;
2 
3use crate::models::Post;
4 
5pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Post>> {
6 // Returns a 404 response automatically if no post has this ID...
7 let post = Post::find_or_fail(id).await?;
8 
9 Ok(Json(post))
10}

When a model's ID comes directly from a route parameter like this, you'll usually let route model binding load the model and return the 404 for you automatically.

To retrieve multiple models by their primary keys in a single query, pass a list of keys to find_many:

1let posts = Post::find_many([1, 2, 3]).await?;
1let posts = Post::find_many([1, 2, 3]).await?;

To retrieve the first model matching a condition, use first_where, or chain first or first_or_fail onto a query. Like find_or_fail, first_or_fail responds with a 404 when no row matches:

1let post = Post::first_where(Post::title.eq("Hello")).await?;
2 
3let post = Post::query()
4 .filter(Post::votes.gt(100))
5 .order_by(Post::published_at.desc())
6 .first()
7 .await?;
8 
9let post = Post::query()
10 .filter(Post::slug.eq(slug))
11 .first_or_fail()
12 .await?;
1let post = Post::first_where(Post::title.eq("Hello")).await?;
2 
3let post = Post::query()
4 .filter(Post::votes.gt(100))
5 .order_by(Post::published_at.desc())
6 .first()
7 .await?;
8 
9let post = Post::query()
10 .filter(Post::slug.eq(slug))
11 .first_or_fail()
12 .await?;

When you already have a collection of models and need their primary keys, call keys() on the slice or Vec to extract them in order:

1let users = User::query()
2 .order_by(User::name)
3 .limit(10)
4 .get()
5 .await?;
6 
7let posts = Post::query()
8 .filter(Post::user_id.is_in(users.keys()))
9 .get()
10 .await?;
1let users = User::query()
2 .order_by(User::name)
3 .limit(10)
4 .get()
5 .await?;
6 
7let posts = Post::query()
8 .filter(Post::user_id.is_in(users.keys()))
9 .get()
10 .await?;

To retrieve a single column's values without hydrating full models, pass a typed column to pluck (returning Vec<T>) or value (returning Option<T>). Both infer the column's exact Rust type automatically:

1let titles = Post::query()
2 .order_by(Post::title)
3 .pluck(Post::title)
4 .await?;
5 
6let title = Post::query()
7 .filter(Post::id.eq(1))
8 .value(Post::title)
9 .await?;
1let titles = Post::query()
2 .order_by(Post::title)
3 .pluck(Post::title)
4 .await?;
5 
6let title = Post::query()
7 .filter(Post::id.eq(1))
8 .value(Post::title)
9 .await?;

Because hydrating a model requires every column, model queries always select all columns and do not expose select or add_select. To include computed values from related records, such as each post's comment count, use with_count and other relationship aggregates. To select only a subset of columns into a custom struct, use db::table instead.

Filtering with typed columns

#[model] generates a typed column constant for every field on your struct, such as Post::title and Post::votes. Each column provides type-checked comparison methods like eq, ne, lt, gt, is_in, and is_null, so comparing a column against the wrong type fails at compile time:

1let posts = Post::query()
2 .filter(Post::user_id.eq(user.id))
3 .filter(Post::votes.ge(10))
4 .filter(Post::published_at.is_not_null())
5 .get()
6 .await?;
7 
8let selected = Post::query()
9 .filter(Post::id.is_in([1, 2, 3]))
10 .filter(Post::title.ne("Draft"))
11 .get()
12 .await?;
1let posts = Post::query()
2 .filter(Post::user_id.eq(user.id))
3 .filter(Post::votes.ge(10))
4 .filter(Post::published_at.is_not_null())
5 .get()
6 .await?;
7 
8let selected = Post::query()
9 .filter(Post::id.is_in([1, 2, 3]))
10 .filter(Post::title.ne("Draft"))
11 .get()
12 .await?;

Each comparison accepts an owned value, a reference, or another column of the same type; String columns also accept &str, and Option<T> columns accept T. Combine conditions with &, |, and !:

1let posts = Post::query()
2 .filter(Post::title.starts_with("Laravel") & Post::votes.ge(10))
3 .filter(Post::updated_at.gt(Post::created_at))
4 .order_by(Post::votes.desc())
5 .get()
6 .await?;
1let posts = Post::query()
2 .filter(Post::title.starts_with("Laravel") & Post::votes.ge(10))
3 .filter(Post::updated_at.gt(Post::created_at))
4 .order_by(Post::votes.desc())
5 .get()
6 .await?;

Here are all of the comparison and ordering methods available on typed columns:

Method Columns SQL
eq, ne, lt, le, gt, ge Every column =, <>, <, <=, >, >=
is_in(values), is_not_in(values) Every column in (...), not in (...). An empty is_in matches no rows, an empty is_not_in matches every row, and a subquery matches the rows it returns
between(low, high) Every column between ... and ...
is_null(), is_not_null() Option<T> columns is null, is not null
like(pattern) String and Option<String> columns like, where % and _ are wildcards
like_case_sensitive(pattern) String and Option<String> columns Case-sensitive like across all databases
starts_with, ends_with, contains String and Option<String> columns like, where % and _ in the text match only themselves
is_past(), is_future() Timestamp and Option<Timestamp> columns < or > the current time
is_today(), is_before_today(), is_after_today() Timestamp and Option<Timestamp> columns The column's date =, <, or > today's date in UTC
asc(), desc() Every column An ordering

You may also pass typed columns anywhere the query builder expects a column, including order_by, pluck, and group_by([Post::user_id]).

When you need a SQL condition that typed columns do not model, combine them with db::raw!:

1use laravel::db;
2 
3let posts = Post::query()
4 .filter(Post::votes.gt(100) & db::raw!("extract(dow from created_at) = 1"))
5 .get()
6 .await?;
1use laravel::db;
2 
3let posts = Post::query()
4 .filter(Post::votes.gt(100) & db::raw!("extract(dow from created_at) = 1"))
5 .get()
6 .await?;

Aggregates

Model queries support the same aggregate methods as db::table, including count, exists, sum, avg, min, and max:

1let published = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .count()
4 .await?;
5 
6let has_drafts = Post::query()
7 .filter(Post::published_at.is_null())
8 .exists()
9 .await?;
10 
11let total_votes: Option<i64> = Post::query().sum(Post::votes).await?;
12let average_votes: Option<f64> = Post::query().avg(Post::votes).await?;
13let top_votes: Option<i64> = Post::query().max(Post::votes).await?;
1let published = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .count()
4 .await?;
5 
6let has_drafts = Post::query()
7 .filter(Post::published_at.is_null())
8 .exists()
9 .await?;
10 
11let total_votes: Option<i64> = Post::query().sum(Post::votes).await?;
12let average_votes: Option<f64> = Post::query().avg(Post::votes).await?;
13let top_votes: Option<i64> = Post::query().max(Post::votes).await?;

Comparing with subqueries

Sometimes the value you want to compare against lives in another table or requires an aggregate across rows. For example, you might list the posts written by anyone who has commented on a featured post, or the posts with more votes than the site's average. Rather than loading those values first, call select_column on a model query to narrow it to a single column or aggregate expression, and pass it to is_in or any comparison so the database runs it as a subquery:

1let commented = Comment::query()
2 .join("posts", Post::id.eq(Comment::post_id))
3 .filter(Post::featured.eq(true))
4 .select_column(Comment::user_id);
5 
6let posts = Post::query()
7 .filter(Post::user_id.is_in(commented))
8 .get()
9 .await?;
10 
11let average = Post::query().select_column(Post::votes.avg());
12 
13let popular = Post::query()
14 .filter(Post::votes.gt(average))
15 .get()
16 .await?;
1let commented = Comment::query()
2 .join("posts", Post::id.eq(Comment::post_id))
3 .filter(Post::featured.eq(true))
4 .select_column(Comment::user_id);
5 
6let posts = Post::query()
7 .filter(Post::user_id.is_in(commented))
8 .get()
9 .await?;
10 
11let average = Post::query().select_column(Post::votes.avg());
12 
13let popular = Post::query()
14 .filter(Post::votes.gt(average))
15 .get()
16 .await?;

You may pass any typed column, column aggregate (count, count_distinct, sum, avg, min, max), or db::table query selecting a single column.

Paginating results

When displaying a long list of models, call paginate on a model query to return a single page of records along with page links and totals:

1let posts = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .order_by(Post::published_at.desc())
4 .paginate(15)
5 .await?;
1let posts = Post::query()
2 .filter(Post::published_at.is_not_null())
3 .order_by(Post::published_at.desc())
4 .paginate(15)
5 .await?;

You may also call simple_paginate for previous/next pagination without a total count query, or cursor_paginate for cursor-based pagination on large datasets. To learn more about rendering pagination links, infinite scroll, and customizing page URLs, check out the pagination guide.

Scopes

If you find yourself reusing the same filter across queries, such as popular or published posts, you can define a scope as an associated function on your model returning db::Condition, then pass it to filter:

1use laravel::db::Condition;
2 
3impl Post {
4 pub fn popular() -> Condition {
5 Post::votes.gt(100)
6 }
7 
8 pub fn is_published() -> Condition {
9 Post::published_at.is_not_null()
10 }
11}
12 
13let posts = Post::query()
14 .filter(Post::popular() & Post::is_published())
15 .get()
16 .await?;
1use laravel::db::Condition;
2 
3impl Post {
4 pub fn popular() -> Condition {
5 Post::votes.gt(100)
6 }
7 
8 pub fn is_published() -> Condition {
9 Post::published_at.is_not_null()
10 }
11}
12 
13let posts = Post::query()
14 .filter(Post::popular() & Post::is_published())
15 .get()
16 .await?;

Because #[model] defines a typed column constant for every field, give scopes distinct names from column fields (such as is_published rather than published_at).

Scopes may also accept parameters, such as filtering posts by a specific author:

1impl Post {
2 pub fn by(user: &User) -> Condition {
3 Post::user_id.eq(user.id)
4 }
5}
6 
7let posts = Post::query()
8 .filter(Post::by(&user) & Post::is_published())
9 .get()
10 .await?;
1impl Post {
2 pub fn by(user: &User) -> Condition {
3 Post::user_id.eq(user.id)
4 }
5}
6 
7let posts = Post::query()
8 .filter(Post::by(&user) & Post::is_published())
9 .get()
10 .await?;

If a reusable scope needs to apply ordering, limits, or eager loads in addition to filters, accept and return Builder<Self>, and chain it onto any query with scope:

1use laravel::db::Builder;
2 
3impl Post {
4 pub fn trending(query: Builder<Post>) -> Builder<Post> {
5 query.filter(Post::votes.gt(10)).order_by(Post::votes.desc()).limit(10)
6 }
7}
8 
9let posts = Post::query()
10 .filter(Post::is_published())
11 .scope(Post::trending)
12 .get()
13 .await?;
1use laravel::db::Builder;
2 
3impl Post {
4 pub fn trending(query: Builder<Post>) -> Builder<Post> {
5 query.filter(Post::votes.gt(10)).order_by(Post::votes.desc()).limit(10)
6 }
7}
8 
9let posts = Post::query()
10 .filter(Post::is_published())
11 .scope(Post::trending)
12 .get()
13 .await?;

Chunking and streaming

When a console command or background job needs to process tens of thousands of models, loading them all into memory at once is impractical. Instead, stream models in pages with chunk_by_id, which paginates by primary key so it remains safe even if your loop updates or deletes rows as it goes:

1use laravel::stream::TryStreamExt;
2 
3let mut pages = Post::query().filter(Post::votes.eq(0)).chunk_by_id(100);
4 
5while let Some(posts) = pages.try_next().await? {
6 for post in posts {
7 post.delete().await?;
8 }
9}
1use laravel::stream::TryStreamExt;
2 
3let mut pages = Post::query().filter(Post::votes.eq(0)).chunk_by_id(100);
4 
5while let Some(posts) = pages.try_next().await? {
6 for post in posts {
7 post.delete().await?;
8 }
9}

lazy_by_id yields the same paged results one model at a time, and chunk paginates using the query's own order_by clause. Use chunk_by_id_desc or lazy_by_id_desc to walk primary keys from highest to lowest. All of these chunked methods eager-load any relationships requested with with for each page. By contrast, cursor streams individual rows over a single query and therefore cannot eager-load relationships.

Ordering results

To sort model queries, pass a typed column to order_by (ascending by default, or call .desc() for descending order). Chaining multiple order_by calls adds tie-breakers in order:

1let posts = Post::query()
2 .order_by(Post::votes.desc())
3 .order_by(Post::title)
4 .get()
5 .await?;
1let posts = Post::query()
2 .order_by(Post::votes.desc())
3 .order_by(Post::title)
4 .get()
5 .await?;

For sorting by a timestamp column, latest orders newest first and oldest orders oldest first:

1let posts = Post::query().latest(Post::created_at).limit(10).get().await?;
1let posts = Post::query().latest(Post::created_at).limit(10).get().await?;

Sometimes you need to sort rows in a custom domain order rather than alphabetically or numerically. For example, a support queue should display urgent tickets before high-priority tickets, even though "urgent" sorts after "high" alphabetically:

1// src/models/ticket.rs
2use laravel::prelude::*;
3use laravel::model::model;
4use laravel::time::Timestamp;
5use serde::{Deserialize, Serialize};
6 
7#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
8#[serde(rename_all = "snake_case")]
9pub enum Priority {
10 Low,
11 Medium,
12 High,
13 Urgent,
14}
15 
16#[model]
17pub struct Ticket {
18 pub id: i64,
19 pub priority: Priority,
20 pub created_at: Timestamp,
21}
1// src/models/ticket.rs
2use laravel::prelude::*;
3use laravel::model::model;
4use laravel::time::Timestamp;
5use serde::{Deserialize, Serialize};
6 
7#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
8#[serde(rename_all = "snake_case")]
9pub enum Priority {
10 Low,
11 Medium,
12 High,
13 Urgent,
14}
15 
16#[model]
17pub struct Ticket {
18 pub id: i64,
19 pub priority: Priority,
20 pub created_at: Timestamp,
21}

Use in_order_of to sort rows according to the position of their column value in a list. Any rows whose value is not in the list appear last:

1use crate::models::{Priority, Ticket};
2 
3let tickets = Ticket::query()
4 .in_order_of(Ticket::priority, [Priority::Urgent, Priority::High])
5 .order_by(Ticket::created_at)
6 .get()
7 .await?;
1use crate::models::{Priority, Ticket};
2 
3let tickets = Ticket::query()
4 .in_order_of(Ticket::priority, [Priority::Urgent, Priority::High])
5 .order_by(Ticket::created_at)
6 .get()
7 .await?;

This query returns urgent tickets first, followed by high-priority tickets, and then low and medium tickets together (ordered oldest first within each group). Because in_order_of is type-checked against the column, [Priority::Urgent] compiles while ["urgent"] does not.

Comparing models

To check whether two model instances represent the same database record, such as checking whether a comment's author also wrote the post, call is or is_not. Loaded #[belongs_to] and #[has_one] relationships support both methods directly:

1let post = Post::query()
2 .with(Post::user)
3 .with(Post::comments.with(Comment::user))
4 .find_or_fail(id)
5 .await?;
6 
7for comment in &post.comments {
8 let from_author = comment.user.is(&post.user);
9}
1let post = Post::query()
2 .with(Post::user)
3 .with(Post::comments.with(Comment::user))
4 .find_or_fail(id)
5 .await?;
6 
7for comment in &post.comments {
8 let from_author = comment.user.is(&post.user);
9}

is compares only the models' primary keys and database connections, so a user loaded from an archive connection is not considered equal to a user with the same key on the default connection, while a model whose other columns were updated still matches its original record. If you want value-level comparison across every field (for example in tests), derive PartialEq and use ==. When a #[belongs_to] relationship is not loaded, compare the foreign key directly (post.user_id == user.id).

Route model binding

Routes that inspect or modify a model typically include its key in the URL, such as /posts/42. Instead of querying the post manually, declare it as a handler parameter. Laravel resolves the model from the route parameter matching the struct name in snake case: {post} for Post, or {blog_post} for BlogPost:

1// src/routes/web.rs
2route.get("/posts/{post}", posts::show);
1// src/routes/web.rs
2route.get("/posts/{post}", posts::show);
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn show(post: Post) -> Page {
6 inertia::render("Posts/Show", props! { post })
7}
1use laravel::inertia::{self, Page, props};
2 
3use crate::models::Post;
4 
5pub async fn show(post: Post) -> Page {
6 inertia::render("Posts/Show", props! { post })
7}

Laravel matches the parameter against the model's primary key or configured route_key. A missing record or an unparseable value, such as /posts/hello for an i64 key, returns a 404 response automatically.

You may also pass a model directly to route! and redirect! in place of its raw key:

1// "/posts/42", or "/posts/hello-world" with route_key = "slug"
2Ok(redirect!(posts::show, &post))
1// "/posts/42", or "/posts/hello-world" with route_key = "slug"
2Ok(redirect!(posts::show, &post))

When a route binds two parameters of the same model type, such as /users/{user}/friends/{friend}, extract one as user: User and resolve the other with request.model::<User>("friend").await?.

Customizing the key

Sometimes a single route should resolve a model by a different column. For example, a public blog route might look up posts by slug while admin routes continue using the primary key. Specify the column name after a colon in the route parameter while still extracting post: Post in the handler:

1// src/routes/web.rs
2route.get("/blog/{post:slug}", blog::show);
3route.get("/admin/posts/{post}", admin::posts::show);
1// src/routes/web.rs
2route.get("/blog/{post:slug}", blog::show);
3route.get("/admin/posts/{post}", admin::posts::show);

Laravel parses the route segment using that column's Rust type, which must be text, an integer, a UUID, or a ULID. Naming a field that does not exist on the model fails with a 500 error naming the unknown field.

URL generation respects each route's parameter syntax automatically, so passing the same Post generates the right URL for both routes:

1route!(blog::show, &post)?; // "http://localhost/blog/hello-world"
2route!(admin::posts::show, &post)?; // "http://localhost/admin/posts/42"
1route!(blog::show, &post)?; // "http://localhost/blog/hello-world"
2route!(admin::posts::show, &post)?; // "http://localhost/admin/posts/42"

If every route should bind a model by the same column, set route_key on #[model] instead as shown in Table and column names.

Nested models

A route can nest one model under another, such as /users/{user}/blog/{post:slug}. When the child parameter uses a custom key like {post:slug}, Laravel scopes the post to that user automatically. A request for another user's post returns 404, allowing two users to each own a post with the slug hello-world:

1route.get("/users/{user}/blog/{post:slug}", blog::show);
2 
3pub async fn show(user: User, post: Post) -> Page {
4 inertia::render("Posts/Show", props! { user, post })
5}
1route.get("/users/{user}/blog/{post:slug}", blog::show);
2 
3pub async fn show(user: User, post: Post) -> Page {
4 inertia::render("Posts/Show", props! { user, post })
5}

When the child parameter binds by primary key (as in /users/{user}/posts/{post}), Laravel binds it independently by default. To require that the child belong to the parent, call scope_bindings on the route or nested resource!:

1route.get("/users/{user}/posts/{post}", posts::show).scope_bindings();
2 
3resource!(users::posts).scope_bindings();
1route.get("/users/{user}/posts/{post}", posts::show).scope_bindings();
2 
3resource!(users::posts).scope_bindings();

To enable scoped bindings for an entire group of routes, call scope_bindings before group:

1route.scope_bindings().group(|route| {
2 route.get("/users/{user}/posts/{post}", posts::show);
3 route.get("/teams/{team}/members/{user}", members::show);
4});
1route.scope_bindings().group(|route| {
2 route.get("/users/{user}/posts/{post}", posts::show);
3 route.get("/teams/{team}/members/{user}", members::show);
4});

Laravel resolves the scoped child through a relationship connecting the two models. First, it looks for a relationship on the parent matching the pluralized child parameter name (such as User::posts for {post}), supporting #[has_one], #[has_many], #[belongs_to_many], and through relationships. With scope_bindings, /teams/{team}/members/{user} matches only members of that team, and /projects/{project}/deployments/{deployment} matches only deployments belonging to that project's environments. If the parent has no matching relationship name, Laravel falls back to the child's #[belongs_to] relationship pointing to the parent, or to the sole relationship between the two models. Has-one-of-many relationships such as latest_order are never used to scope bindings, and filtered relationships such as admins never shadow an unfiltered relationship such as members.

The parent parameter is the parameter immediately preceding the child, named after its model (such as {user} for User). You may also name the parent parameter after a #[belongs_to] relationship on the child, such as {author} when Post declares an author relationship:

1use laravel::model::{BelongsTo, model};
2 
3#[model]
4pub struct Post {
5 pub id: i64,
6 pub author_id: i64,
7 pub title: String,
8 #[belongs_to]
9 pub author: BelongsTo<User>,
10}
1use laravel::model::{BelongsTo, model};
2 
3#[model]
4pub struct Post {
5 pub id: i64,
6 pub author_id: i64,
7 pub title: String,
8 #[belongs_to]
9 pub author: BelongsTo<User>,
10}
1route.get("/authors/{author}/posts/{post}", posts::show).scope_bindings();
1route.get("/authors/{author}/posts/{post}", posts::show).scope_bindings();

In this handler, extract post: Post and look up the author with request.model::<User>("author").await?.

If two models share multiple relationships and none matches the parameter names, Laravel responds with a 500 error listing the ambiguous relationships. If no relationship exists between the two models, the child binds without scoping.

To disable automatic scoping on a route with a custom key, call without_scoped_bindings on the route or group:

1route.get("/users/{user}/blog/{post:slug}", blog::show).without_scoped_bindings();
1route.get("/users/{user}/blog/{post:slug}", blog::show).without_scoped_bindings();

A route-level call overrides its group's setting, so an individual route inside a scope_bindings group can opt out with without_scoped_bindings and vice versa.

Creating models

create! inserts a row and returns the stored model populated with its generated key, timestamps, and database defaults. This handler creates a post for the logged-in user:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn store(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
7 let post = create!(Post { title: "My first post", user: &user }).await?;
8 
9 Ok(redirect!(posts::show, &post))
10}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn store(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
7 let post = create!(Post { title: "My first post", user: &user }).await?;
8 
9 Ok(redirect!(posts::show, &post))
10}

Each field sets the column of the same name, and any omitted columns receive NULL or their database default. Shorthand field syntax works as in standard Rust struct literals, and a #[belongs_to] relationship accepts the related model so user: &user populates user_id.

Each field accepts a value of its column's type or a reference to clone from, along with common conversions: &str for String, T for Option<T>, laravel::now() for Timestamp, and a plain-text password or Password for PasswordHash, which Laravel hashes with hash::make before storing. If a value does not match the column, the compiler error lists the accepted types.

Fill structs

When creating models from request input, a client can submit fields your form never rendered. Allowing arbitrary fields to populate a model would let an attacker send is_admin=1 and escalate their privileges.

A fill struct explicitly lists the columns a request is allowed to write. Annotate it with #[laravel::input(fills = Post)] to target the model and derive Deserialize, Validate, and Fill, then spread ..input at the end of create!:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6#[laravel::input(fills = Post)]
7#[validate(authenticated)]
8pub struct NewPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn store(
16 Authenticated(user): Authenticated<User>,
17 Valid(input): Valid<NewPost>,
18) -> laravel::Result<Redirect> {
19 let post = create!(Post { user: &user, ..input }).await?;
20 
21 Ok(redirect!(posts::show, &post))
22}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6#[laravel::input(fills = Post)]
7#[validate(authenticated)]
8pub struct NewPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn store(
16 Authenticated(user): Authenticated<User>,
17 Valid(input): Valid<NewPost>,
18) -> laravel::Result<Redirect> {
19 let post = create!(Post { user: &user, ..input }).await?;
20 
21 Ok(redirect!(posts::show, &post))
22}

Because a fill struct only writes the fields you declare on it, columns like user_id cannot be tampered with by the client. Define a dedicated fill struct for each form containing only the fields that form is allowed to modify. Explicit fields placed before ..input override values from input, matching Rust's struct update syntax.

Two field attributes customize how a field maps to the model:

  • #[fill(column = "nickname")] maps the form field to a differently named column on the model.
  • #[fill(skip)] excludes the field from the model write, which is useful for extra inputs like tag_ids that you handle separately.

If you need to keep using input after creating the model, such as reading a #[fill(skip)] field, borrow it with ..&input instead. For example, this handler creates a post and then attaches tags through a #[belongs_to_many] relationship:

1use crate::models::Tag;
2 
3#[laravel::input(fills = Post)]
4#[validate(authenticated)]
5pub struct NewPost {
6 #[validate(required, max_length(255))]
7 pub title: String,
8 #[fill(skip)]
9 #[serde(default)]
10 #[validate(max_items(10), each(exists(Tag::id)))]
11 pub tag_ids: Vec<i64>,
12}
13 
14pub async fn store(
15 Authenticated(user): Authenticated<User>,
16 Valid(input): Valid<NewPost>,
17) -> laravel::Result<Redirect> {
18 let post = create!(Post { user: &user, ..&input }).await?;
19 
20 post.tags().attach(&input.tag_ids).await?;
21 
22 Ok(redirect!(posts::show, &post))
23}
1use crate::models::Tag;
2 
3#[laravel::input(fills = Post)]
4#[validate(authenticated)]
5pub struct NewPost {
6 #[validate(required, max_length(255))]
7 pub title: String,
8 #[fill(skip)]
9 #[serde(default)]
10 #[validate(max_items(10), each(exists(Tag::id)))]
11 pub tag_ids: Vec<i64>,
12}
13 
14pub async fn store(
15 Authenticated(user): Authenticated<User>,
16 Valid(input): Valid<NewPost>,
17) -> laravel::Result<Redirect> {
18 let post = create!(Post { user: &user, ..&input }).await?;
19 
20 post.tags().attach(&input.tag_ids).await?;
21 
22 Ok(redirect!(posts::show, &post))
23}

update!(post { ..&input }) and the builder's fill(&input) accept a borrowed reference as well.

When building partial-update endpoints that only submit changed fields, wrap optional form fields in Sometimes<T>. To learn more, check out Updating only the fields a request sends.

To learn more about #[laravel::input] structs, validation rules, authorization, and custom error messages, check out the validation guide.

Fill structs outside a request

When a fill struct doesn't come from an HTTP request, such as a domain struct used by a console command or background job, derive Fill directly with #[fills(Post)], and add Validate if you also want to check its fields with validate:

1use laravel::model::{Fill, create};
2use laravel::validation::Validate;
3 
4use crate::models::{Post, User};
5 
6#[derive(Validate, Fill)]
7#[fills(Post)]
8pub struct PublishPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn publish(author: &User, input: PublishPost) -> laravel::Result<Post> {
16 input.validate().await?;
17 
18 create!(Post {
19 user: author,
20 ..input
21 })
22 .await
23}
1use laravel::model::{Fill, create};
2use laravel::validation::Validate;
3 
4use crate::models::{Post, User};
5 
6#[derive(Validate, Fill)]
7#[fills(Post)]
8pub struct PublishPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11 #[validate(required)]
12 pub body: String,
13}
14 
15pub async fn publish(author: &User, input: PublishPost) -> laravel::Result<Post> {
16 input.validate().await?;
17 
18 create!(Post {
19 user: author,
20 ..input
21 })
22 .await
23}

Required columns

Every non-nullable column is required unless it carries #[default], is a generated primary key, or is a managed timestamp. If you omit a required column in create!, compilation fails with a message listing the missing fields:

1error[E0080]: evaluation panicked: can't create a `Post` without `user` (or `user_id`) and `title`
1error[E0080]: evaluation panicked: can't create a `Post` without `user` (or `user_id`) and `title`

When a required column is supplied dynamically by a fill struct, a creating hook, or a relationship builder such as user.posts(), Laravel defers the check until runtime and returns an error before executing the insert if anything is missing. You may also opt out of the compile-time check explicitly by ending the fields with .., as shown in first_or_create.

Passing a struct literal for a relationship field inside create! inserts that related record automatically. Laravel inserts #[belongs_to] parents before the main row, and inserts #[has_one], #[has_many], #[belongs_to_many], and their polymorphic counterparts afterward:

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

To insert multiple models of the same type at once, pass a bracketed list to create!, which returns a Vec of the created models in order:

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

Both forms wrap all inserts in a single transaction so any failure rolls everything back. The returned models already have their newly created relationships hydrated in memory, so reading post.user above requires no extra query, and child models created alongside a parent already hold that parent in their #[belongs_to] or #[morph_to] field.

Building a create in steps

When the columns to set depend on runtime conditions, use the builder returned by Post::create() instead of create!. It exposes a setter for every column and relationship, plus .fill(input) as the builder equivalent of ..input. This version of the store handler publishes the post immediately if the author's email is verified:

1use laravel::prelude::*;
2 
3use crate::models::{Post, User};
4 
5pub async fn store(
6 Authenticated(user): Authenticated<User>,
7 Valid(input): Valid<NewPost>,
8) -> laravel::Result<Redirect> {
9 let mut create = Post::create().user(&user).fill(input);
10 
11 if user.email_verified_at.is_some() {
12 create = create.published_at(laravel::now());
13 }
14 
15 let post = create.await?;
16 
17 Ok(redirect!(posts::show, &post))
18}
1use laravel::prelude::*;
2 
3use crate::models::{Post, User};
4 
5pub async fn store(
6 Authenticated(user): Authenticated<User>,
7 Valid(input): Valid<NewPost>,
8) -> laravel::Result<Redirect> {
9 let mut create = Post::create().user(&user).fill(input);
10 
11 if user.email_verified_at.is_some() {
12 create = create.published_at(laravel::now());
13 }
14 
15 let post = create.await?;
16 
17 Ok(redirect!(posts::show, &post))
18}

Finding or creating models

Sometimes you want to retrieve an existing record matching a condition, or insert it if no match exists (such as looking up a user by email). Pass a condition and a create! expression or fill struct to first_or_create:

1use laravel::model::create;
2 
3use crate::models::User;
4 
5let user = User::first_or_create(
6 User::email.eq(email),
7 create!(User { name, password, .. }),
8)
9.await?;
1use laravel::model::create;
2 
3use crate::models::User;
4 
5let user = User::first_or_create(
6 User::email.eq(email),
7 create!(User { name, password, .. }),
8)
9.await?;

When inserting a new row, Laravel automatically copies any eq values combined with & from the lookup condition, so you do not need to repeat email inside create! (the trailing .. tells create! that the condition supplies it). Non-equality clauses such as gt or | are used only for the lookup.

update_or_create accepts the same arguments, but updates the matching row with the provided values if it already exists instead of returning it unchanged:

1let user = User::update_or_create(
2 User::email.eq("[email protected]"),
3 create!(User { name: "Taylor Otwell", password: "secret", .. }),
4)
5.await?;
1let user = User::update_or_create(
2 User::email.eq("[email protected]"),
3 create!(User { name: "Taylor Otwell", password: "secret", .. }),
4)
5.await?;

When you need to know whether the record was newly created or already existed (for example, to send a welcome email only on creation), chain .found_or_created() before awaiting. It returns FoundOrCreated::Created(model) or FoundOrCreated::Found(model):

1use laravel::mail;
2use laravel::model::FoundOrCreated;
3 
4use crate::mail::Welcome;
5 
6let user = User::first_or_create(User::email.eq(email), create!(User { name, password, .. }))
7 .found_or_created()
8 .await?;
9 
10if let FoundOrCreated::Created(user) = &user {
11 mail::to(user).queue(Welcome::new(user)?).await?;
12}
13 
14let user = user.into_model();
1use laravel::mail;
2use laravel::model::FoundOrCreated;
3 
4use crate::mail::Welcome;
5 
6let user = User::first_or_create(User::email.eq(email), create!(User { name, password, .. }))
7 .found_or_created()
8 .await?;
9 
10if let FoundOrCreated::Created(user) = &user {
11 mail::to(user).queue(Welcome::new(user)?).await?;
12}
13 
14let user = user.into_model();

If another concurrent request inserts the row between the lookup and the insert, the losing request resolves to Found, ensuring the welcome email is sent only once.

Add a unique index on the lookup columns (such as email) so concurrent requests cannot insert duplicate rows. With a unique index in place, Laravel catches the constraint violation from the losing insert and fetches the winning row automatically.

Inserting many rows

When importing a large batch of records, inserting them one by one with create! is slow and you rarely need every hydrated model back. Use insert with the row! macro (or a list of fill structs) to write all rows in a single SQL statement and return the number of inserted rows:

1use laravel::model::row;
2 
3use crate::models::User;
4 
5let inserted = User::insert(row!([
6 User { email: "[email protected]", name: "Taylor", password: "secret" },
7 User { email: "[email protected]", name: "Abigail", password: "secret" },
8]))
9.await?;
1use laravel::model::row;
2 
3use crate::models::User;
4 
5let inserted = User::insert(row!([
6 User { email: "[email protected]", name: "Taylor", password: "secret" },
7 User { email: "[email protected]", name: "Abigail", password: "secret" },
8]))
9.await?;

When inserting a dynamic list of records, such as rows parsed from a CSV, map each item with a single-row row!(User { .. }) instead:

1let rows = imports.into_iter().map(|item| {
2 row!(User {
3 email: item.email,
4 name: item.name,
5 password: item.password,
6 })
7});
8 
9let inserted = User::insert(rows).await?;
1let rows = imports.into_iter().map(|item| {
2 row!(User {
3 email: item.email,
4 name: item.name,
5 password: item.password,
6 })
7});
8 
9let inserted = User::insert(rows).await?;

insert still sets timestamps and hashes PasswordHash columns automatically. row! verifies required columns at compile time, while fill structs are validated before the statement executes.

When some incoming rows may already exist, use upsert to insert new rows and update existing ones in a single statement. Pass the rows, the unique columns that identify existing records, and the columns to update on conflict:

1let rows = row!([
2 User { email: "[email protected]", name: "Taylor Otwell", password: "secret" },
3 User { email: "[email protected]", name: "Jess", password: "secret" },
4]);
5 
6let affected = User::upsert(rows, [User::email], [User::name]).await?;
1let rows = row!([
2 User { email: "[email protected]", name: "Taylor Otwell", password: "secret" },
3 User { email: "[email protected]", name: "Jess", password: "secret" },
4]);
5 
6let affected = User::upsert(rows, [User::email], [User::name]).await?;

Because typed columns carry their Rust type, Rust arrays only accept columns of the same type. When matching on or updating columns with different types (such as a String and an Option<Timestamp>), pass a tuple instead:

1// Same column types (`i64` and `i64`): pass an array...
2Post::upsert(posts, [Post::id], [Post::votes, Post::views]).await?;
3 
4// Mixed column types (`String` and `Option<Timestamp>`): pass a tuple...
5User::upsert(users, [User::email], (User::name, User::email_verified_at)).await?;
1// Same column types (`i64` and `i64`): pass an array...
2Post::upsert(posts, [Post::id], [Post::votes, Post::views]).await?;
3 
4// Mixed column types (`String` and `Option<Timestamp>`): pass a tuple...
5User::upsert(users, [User::email], (User::name, User::email_verified_at)).await?;

When a user with a matching email already exists, upsert updates only name and updated_at while leaving all other columns untouched. PostgreSQL and SQLite require a unique index on the identifying columns. MySQL and MariaDB detect conflicts using every primary or unique index on the table, as with the query builder's upsert.

Because insert and upsert write rows without hydrating models, they do not run hooks, dispatch events, or create nested related models (pass an existing parent such as user: &user instead).

Replicating models

When you want to create a new record that shares most of its attributes with an existing model, such as duplicating a shipping address as a billing address, spread ..shipping.replicate() at the end of create! and override only the fields that differ:

1use laravel::model::create;
2 
3use crate::models::Address;
4 
5let shipping = create!(Address {
6 kind: "shipping",
7 line_1: "123 Example Street",
8 city: "Victorville",
9 state: "CA",
10 postcode: "90001",
11})
12.await?;
13 
14let billing = create!(Address { kind: "billing", ..shipping.replicate() }).await?;
1use laravel::model::create;
2 
3use crate::models::Address;
4 
5let shipping = create!(Address {
6 kind: "shipping",
7 line_1: "123 Example Street",
8 city: "Victorville",
9 state: "CA",
10 postcode: "90001",
11})
12.await?;
13 
14let billing = create!(Address { kind: "billing", ..shipping.replicate() }).await?;

The new row receives a fresh primary key and timestamps, and any fields before ..shipping.replicate() override the copied columns. Loaded relationships from shipping are not copied because related rows such as orders remain linked to the original row; load them on the new model when needed. A create builder also accepts the copy via .fill(shipping.replicate()).

To exclude specific columns from the copy so they fall back to their database defaults or NULL, chain .except(...) with an array (for columns of one type) or a tuple (for mixed types). For example, this handler duplicates a flight without copying its last flight time or pilot:

1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::Flight;
5 
6pub async fn duplicate(flight: Flight) -> laravel::Result<Redirect> {
7 let copy = create!(Flight {
8 ..flight.replicate().except((Flight::last_flown_at, Flight::last_pilot_id))
9 })
10 .await?;
11 
12 Ok(redirect!(flights::show, &copy))
13}
1use laravel::model::create;
2use laravel::prelude::*;
3 
4use crate::models::Flight;
5 
6pub async fn duplicate(flight: Flight) -> laravel::Result<Redirect> {
7 let copy = create!(Flight {
8 ..flight.replicate().except((Flight::last_flown_at, Flight::last_pilot_id))
9 })
10 .await?;
11 
12 Ok(redirect!(flights::show, &copy))
13}

Updating models

update! modifies an existing model and writes only the columns that changed along with updated_at. For example, this handler resolves a post via route model binding and updates it from a validated form:

1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6#[laravel::input(fills = Post)]
7#[validate(anyone)]
8pub struct EditPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11}
12 
13pub async fn update(
14 mut post: Post,
15 Valid(input): Valid<EditPost>,
16) -> laravel::Result<Redirect> {
17 update!(post { published_at: laravel::now(), ..input }).await?;
18 
19 Ok(redirect!(posts::show, &post))
20}
1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::Post;
5 
6#[laravel::input(fills = Post)]
7#[validate(anyone)]
8pub struct EditPost {
9 #[validate(required, max_length(255))]
10 pub title: String,
11}
12 
13pub async fn update(
14 mut post: Post,
15 Valid(input): Valid<EditPost>,
16) -> laravel::Result<Redirect> {
17 update!(post { published_at: laravel::now(), ..input }).await?;
18 
19 Ok(redirect!(posts::show, &post))
20}

Field assignments follow the same rules as create!: passing None clears an Option column, and passing a related model to a #[belongs_to] field such as user: &other updates user_id. After awaiting, post reflects the updated values in memory. If no field values actually changed, Laravel skips the query, hooks, and events completely.

To update multiple records in a single query, check out Updating many rows.

Updating only the fields a request sends

An Option field writes NULL when omitted from the request. This matches HTML forms, which submit every field and send empty text inputs as null. A JSON PATCH request or an Inertia form sending only changed fields omits untouched fields, so an Option field would clear those columns.

To distinguish omitted fields from explicit null values, declare those fields as Sometimes<T>. Omitted fields decode as Sometimes::Missing and are skipped by ..input, preserving their existing column values, while submitted fields decode as Sometimes::Present. For a Sometimes<Option<T>> field, an explicit null decodes as Present(None) and clears the column. For example, assuming users has a nullable bio column:

1use laravel::model::update;
2use laravel::prelude::*;
3use laravel::validation::Sometimes;
4 
5use crate::models::User;
6 
7#[laravel::input(fills = User)]
8#[validate(authenticated)]
9pub struct EditProfile {
10 #[validate(required, max_length(255))]
11 pub name: Sometimes<String>,
12 #[validate(max_length(1000))]
13 pub bio: Sometimes<Option<String>>,
14}
15 
16pub async fn update(
17 Authenticated(mut user): Authenticated<User>,
18 Valid(input): Valid<EditProfile>,
19) -> laravel::Result<Redirect> {
20 update!(user { ..input }).await?;
21 
22 Ok(Redirect::back())
23}
1use laravel::model::update;
2use laravel::prelude::*;
3use laravel::validation::Sometimes;
4 
5use crate::models::User;
6 
7#[laravel::input(fills = User)]
8#[validate(authenticated)]
9pub struct EditProfile {
10 #[validate(required, max_length(255))]
11 pub name: Sometimes<String>,
12 #[validate(max_length(1000))]
13 pub bio: Sometimes<Option<String>>,
14}
15 
16pub async fn update(
17 Authenticated(mut user): Authenticated<User>,
18 Valid(input): Valid<EditProfile>,
19) -> laravel::Result<Redirect> {
20 update!(user { ..input }).await?;
21 
22 Ok(Redirect::back())
23}

With this form, sending {"name": "Taylor"} updates name without touching bio, whereas sending {"bio": null} clears bio without touching name.

Validation skips any Sometimes field omitted from the request, so required on name means the value cannot be empty when it is present. To learn more about validation rules and helper methods such as present(), check out Fields a request may leave out.

create! also skips missing Sometimes fields so their columns receive database defaults. Omit Sometimes on fields that a creation form must always supply.

Incrementing a column

Counters such as a post's view count are frequently updated by concurrent requests. Using += or -= inside update! emits an atomic database update (such as views = views + 1) so concurrent increments never overwrite each other, and updates the in-memory model afterward:

1update!(post { views += 1 }).await?;
2update!(post { votes -= 1 }).await?;
1update!(post { views += 1 }).await?;
2update!(post { votes -= 1 }).await?;

+= and -= work on integer, floating-point, and Decimal columns. You may also call post.increment(Post::views, 1) or post.decrement(Post::votes, 1) directly.

Building an update in steps

Just as Post::create() builds an insert dynamically, post.update() returns a builder exposing a setter for every column along with fill, increment, and decrement. For example, this code updates a post from a form and clears published_at when saving it as a draft:

1use laravel::time::Timestamp;
2 
3let mut update = post.update().fill(&input);
4 
5if input.draft {
6 update = update.published_at(None::<Timestamp>);
7}
8 
9update.await?;
1use laravel::time::Timestamp;
2 
3let mut update = post.update().fill(&input);
4 
5if input.draft {
6 update = update.published_at(None::<Timestamp>);
7}
8 
9update.await?;

Because an Option column's setter accepts multiple optional types, annotate None with its inner type (such as None::<Timestamp>).

Updating many rows

When you need to apply the same change to every record matching a query, such as publishing all of a user's drafts, pass the query to update! instead of a single model to execute one bulk UPDATE statement without loading rows into memory:

1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn publish_drafts(
7 Authenticated(user): Authenticated<User>,
8) -> laravel::Result<Redirect> {
9 update!(user.posts().filter(Post::published_at.is_null()) {
10 published_at: laravel::now(),
11 })
12 .await?;
13 
14 Ok(Redirect::back())
15}
1use laravel::model::update;
2use laravel::prelude::*;
3 
4use crate::models::{Post, User};
5 
6pub async fn publish_drafts(
7 Authenticated(user): Authenticated<User>,
8) -> laravel::Result<Redirect> {
9 update!(user.posts().filter(Post::published_at.is_null()) {
10 published_at: laravel::now(),
11 })
12 .await?;
13 
14 Ok(Redirect::back())
15}

update! returns the number of affected rows. Fields work like single-model updates, so misspelled columns and mismatched types fail to compile, and views += 1, ..input, and user: &editor all work. Laravel also updates updated_at automatically unless you set it explicitly:

1update!(Post::query().filter(Post::user_id.eq(old_author.id)) {
2 user: &new_author,
3})
4.await?;
5 
6update!(Post::query().filter(!Post::published_at.is_null()) {
7 views += 1,
8})
9.await?;
1update!(Post::query().filter(Post::user_id.eq(old_author.id)) {
2 user: &new_author,
3})
4.await?;
5 
6update!(Post::query().filter(!Post::published_at.is_null()) {
7 views += 1,
8})
9.await?;

Because bulk query updates never instantiate models, they do not run hooks or dispatch events. When listeners must receive events for each changed record, load the models and update them individually.

You may also pass a relationship query to update!, including #[belongs_to_many] relationships, or build a bulk update dynamically with update(), increment, and decrement:

1update!(post.tags() { featured: true }).await?;
2 
3Post::query()
4 .filter(Post::published_at.is_null())
5 .update()
6 .published_at(laravel::now())
7 .await?;
8 
9Post::query()
10 .filter(!Post::published_at.is_null())
11 .increment(Post::views, 1)
12 .await?;
1update!(post.tags() { featured: true }).await?;
2 
3Post::query()
4 .filter(Post::published_at.is_null())
5 .update()
6 .published_at(laravel::now())
7 .await?;
8 
9Post::query()
10 .filter(!Post::published_at.is_null())
11 .increment(Post::views, 1)
12 .await?;

For writes that typed setters cannot express, such as updating a single JSON path or computing a column from another column in SQL, call update_values with db::values!. Your query's filters, table, connection, and updated_at timestamp still apply, though column names and value types are not checked at compile time:

1use laravel::db::{col, values};
2 
3Post::query()
4 .filter(Post::votes.gt(100))
5 .update_values(values! { "options->theme": "dark", score: col("votes") * 2 })
6 .await?;
1use laravel::db::{col, values};
2 
3Post::query()
4 .filter(Post::votes.gt(100))
5 .update_values(values! { "options->theme": "dark", score: col("votes") * 2 })
6 .await?;

Models also provide update_values, which updates the row and reloads it like refresh so the model reflects database-written columns:

1post.update_values(values! { "options->theme": "dark" }).await?;
1post.update_values(values! { "options->theme": "dark" }).await?;

Reloading from the database

If another request, listener, or bulk query updates a record after you loaded it, use fresh to fetch a brand-new Option<Post> from the database (returning None if the row was deleted), or refresh to reload the existing model and any loaded relationships in place:

1let latest: Option<Post> = post.fresh().await?;
2 
3post.refresh().await?;
1let latest: Option<Post> = post.fresh().await?;
2 
3post.refresh().await?;

Deleting models

Call delete on a model to remove its row from the database. Because delete consumes the model by value, Rust prevents you from accidentally using the deleted model afterward:

1post.delete().await?;
1post.delete().await?;

If you already know the primary keys of the records to delete, such as IDs selected in a bulk action, pass them to destroy. It loads each model before deleting it so hooks and events still run, and returns the number of deleted records:

1let deleted = Post::destroy([1, 2, 3]).await?;
1let deleted = Post::destroy([1, 2, 3]).await?;

To delete matching rows directly in SQL without loading them, call delete on a query. It returns the number of deleted rows and, like bulk updates, skips hooks and events:

1let deleted = Post::query()
2 .filter(Post::votes.eq(0))
3 .delete()
4 .await?;
1let deleted = Post::query()
2 .filter(Post::votes.eq(0))
3 .delete()
4 .await?;

Note that calling post.tags().delete() on a #[belongs_to_many] relationship deletes the Tag rows themselves; to only unlink tags from the post, call detach instead.

Model query deletes also support order_by and limit, making it easy to prune old rows in bounded batches. For example, this query deletes the 1,000 oldest posts:

1let deleted = Post::query().oldest(Post::created_at).limit(1000).delete().await?;
1let deleted = Post::query().oldest(Post::created_at).limit(1000).delete().await?;

Bulk updates support order_by and limit as well. For example, this query publishes the ten oldest drafts:

1let drafts = Post::query()
2 .filter(Post::published_at.is_null())
3 .oldest(Post::created_at)
4 .limit(10);
5 
6update!(drafts { published_at: laravel::now() }).await?;
1let drafts = Post::query()
2 .filter(Post::published_at.is_null())
3 .oldest(Post::created_at)
4 .limit(10);
5 
6update!(drafts { published_at: laravel::now() }).await?;

Serializing models

Because #[model] derives Serialize automatically, you can return models directly from JSON endpoints (Json(post)) or pass them to Inertia pages (props! { post }) and views (data! { post }). By default, every column on your struct is included in the serialized output.

To hide a column from serialized responses, such as an internal note or billing identifier, annotate it with #[serde(skip)] (or #[serde(skip_serializing)] if the model also derives Deserialize):

1use laravel::auth::RememberToken;
2use laravel::crypt::Encrypted;
3use laravel::hash::PasswordHash;
4use laravel::model::model;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 pub name: String,
10 pub email: String,
11 #[serde(skip)]
12 pub password: PasswordHash,
13 #[serde(skip)]
14 pub remember_token: Option<RememberToken>,
15 #[serde(skip)]
16 pub api_secret: Option<Encrypted<String>>,
17 #[serde(skip)]
18 pub internal_notes: Option<String>,
19}
1use laravel::auth::RememberToken;
2use laravel::crypt::Encrypted;
3use laravel::hash::PasswordHash;
4use laravel::model::model;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 pub name: String,
10 pub email: String,
11 #[serde(skip)]
12 pub password: PasswordHash,
13 #[serde(skip)]
14 pub remember_token: Option<RememberToken>,
15 #[serde(skip)]
16 pub api_secret: Option<Encrypted<String>>,
17 #[serde(skip)]
18 pub internal_notes: Option<String>,
19}

Sensitive wrapper types (PasswordHash, RememberToken, and Encrypted<T>) deliberately do not implement Serialize, and #[model] rejects them at compile time unless they are marked #[serde(skip)], preventing secrets from leaking to the frontend by accident.

A few fields are skipped automatically without any attribute:

  • Unloaded relationships: BelongsTo, HasOne, HasMany, and other relationship fields are omitted from JSON unless you eager-load them with with (and relationship aggregates such as posts_count appear only when requested with with_count).
  • Framework metadata: Internal fields added by #[model], such as the database connection the record was loaded from, are always skipped.

Standard Serde attributes also work on models: use #[serde(rename = "...")] on a column, #[serde(rename_all = "camelCase")] on the struct (which renames columns, loaded relationships, and relationship aggregates), or #[serde(skip_serializing_if = "Option::is_none")] to omit None values. Derive Deserialize on a model only when you need to deserialize it back from JSON, such as when storing it in the cache.

When an endpoint needs a different JSON shape than your model, such as exposing extra fields only to administrators or including computed properties, define a dedicated response struct deriving Serialize and return it with Json:

1use laravel::prelude::*;
2use serde::Serialize;
3 
4use crate::models::User;
5 
6#[derive(Serialize)]
7pub struct PublicProfile {
8 pub id: i64,
9 pub name: String,
10}
11 
12impl From<User> for PublicProfile {
13 fn from(user: User) -> Self {
14 Self {
15 id: user.id,
16 name: user.name,
17 }
18 }
19}
20 
21pub async fn show(user: User) -> Json<PublicProfile> {
22 Json(user.into())
23}
1use laravel::prelude::*;
2use serde::Serialize;
3 
4use crate::models::User;
5 
6#[derive(Serialize)]
7pub struct PublicProfile {
8 pub id: i64,
9 pub name: String,
10}
11 
12impl From<User> for PublicProfile {
13 fn from(user: User) -> Self {
14 Self {
15 id: user.id,
16 name: user.name,
17 }
18 }
19}
20 
21pub async fn show(user: User) -> Json<PublicProfile> {
22 Json(user.into())
23}

Hooks

Some invariants should apply to every write of a model regardless of where it originates, such as keeping an article's slug in sync with its title or preventing edits to locked articles. Model hooks run before a model write executes and may mutate the pending values or return an error to abort the operation. Annotate the model with #[model(hooks)] and implement Hooks. Every method has a default no-op implementation, so implement only the hooks you need:

1use laravel::model::{Changes, Draft, Hooks, model};
2use laravel::str::Str;
3 
4#[model(hooks)]
5pub struct Article {
6 pub id: i64,
7 pub title: String,
8 pub slug: String,
9 pub locked: bool,
10}
11 
12impl Hooks for Article {
13 async fn creating(article: &mut Draft<Self>) -> laravel::Result<()> {
14 if let Some(slug) = article.get(Article::title).map(|title| title.slug()) {
15 article.set(Article::slug, slug);
16 }
17 
18 Ok(())
19 }
20 
21 async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
22 if changes.has(Article::title) {
23 laravel::abort_if(self.locked, 409)?;
24 
25 self.slug = self.title.slug();
26 }
27 
28 Ok(())
29 }
30 
31 async fn deleting(&self) -> laravel::Result<()> {
32 laravel::abort_if(self.locked, 409)
33 }
34}
1use laravel::model::{Changes, Draft, Hooks, model};
2use laravel::str::Str;
3 
4#[model(hooks)]
5pub struct Article {
6 pub id: i64,
7 pub title: String,
8 pub slug: String,
9 pub locked: bool,
10}
11 
12impl Hooks for Article {
13 async fn creating(article: &mut Draft<Self>) -> laravel::Result<()> {
14 if let Some(slug) = article.get(Article::title).map(|title| title.slug()) {
15 article.set(Article::slug, slug);
16 }
17 
18 Ok(())
19 }
20 
21 async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
22 if changes.has(Article::title) {
23 laravel::abort_if(self.locked, 409)?;
24 
25 self.slug = self.title.slug();
26 }
27 
28 Ok(())
29 }
30 
31 async fn deleting(&self) -> laravel::Result<()> {
32 laravel::abort_if(self.locked, 409)
33 }
34}
Hook Receives Runs
creating A Draft of the columns about to be inserted Before an insert
updating The model with its changes, and the Changes Before an update. The update also writes the changes the hook makes to the model
deleting The model Before the delete

Because no model instance exists before an insert, creating receives a Draft instead of &mut Self. Call draft.get(column) to inspect a pending column value (returning Option) and draft.set(column, value) to modify it. Implementing both creating and updating keeps slug in sync when a record is inserted and whenever its title changes.

Events

After each single-model write, Laravel dispatches a Created<M>, Updated<M>, or Deleted<M> event from laravel::model. Register a listener to react to model writes without coupling side effects to your handlers, such as sending a welcome email whenever a new user signs up:

1// src/listeners/send_welcome_email.rs
2use laravel::event::{Event, listener};
3use laravel::model::Created;
4 
5use crate::models::User;
6 
7#[listener]
8async fn send_welcome_email(event: Event<Created<User>>) -> laravel::Result<()> {
9 let user = &event.model;
10 
11 // Send the welcome email to user.email...
12 
13 Ok(())
14}
1// src/listeners/send_welcome_email.rs
2use laravel::event::{Event, listener};
3use laravel::model::Created;
4 
5use crate::models::User;
6 
7#[listener]
8async fn send_welcome_email(event: Event<Created<User>>) -> laravel::Result<()> {
9 let user = &event.model;
10 
11 // Send the welcome email to user.email...
12 
13 Ok(())
14}

Every model event exposes the affected record on event.model. Inside a transaction, model event listeners wait until the transaction commits and are skipped if it rolls back, preventing emails from going out for failed sign-ups. To run a listener synchronously inside the transaction instead so its own database writes roll back together, annotate it with #[listener(at_dispatch)].

Updated events also include event.changes, detailing which columns changed during the update:

1use laravel::event::{Event, listener};
2use laravel::model::Updated;
3 
4#[listener]
5async fn verify_new_email(event: Event<Updated<User>>) -> laravel::Result<()> {
6 if event.changes.has(User::email) {
7 let previous: &str = event.changes.old(User::email);
8 
9 // Notify the previous address about the change...
10 }
11 
12 Ok(())
13}
1use laravel::event::{Event, listener};
2use laravel::model::Updated;
3 
4#[listener]
5async fn verify_new_email(event: Event<Updated<User>>) -> laravel::Result<()> {
6 if event.changes.has(User::email) {
7 let previous: &str = event.changes.old(User::email);
8 
9 // Notify the previous address about the change...
10 }
11 
12 Ok(())
13}

Use changes.new(column) to inspect the updated value, or iterate over changes to receive each changed column's name alongside its previous and new values (useful for writing audit logs).

To handle an event asynchronously on a queue worker, mark the listener #[listener(queued)]. Laravel serializes only the model's key and reloads the record when the job runs. In a queued listener, changes tracks changed column names without their values, so inspect it with changes.has(column) or changes.columns(). Queued listeners cannot subscribe to Deleted because the record no longer exists in the database. Queued jobs serialize and reload models using the same key-based lookup.

Muting events

To perform a write without dispatching model events (for example, inside a seeder that shouldn't send emails), chain quietly() on a create or update, or call delete_quietly():

1create!(Post { title: "Hello", user: &user }).quietly().await?;
2update!(post { views += 1 }).quietly().await?;
3post.delete_quietly().await?;
1create!(Post { title: "Hello", user: &user }).quietly().await?;
2update!(post { views += 1 }).quietly().await?;
3post.delete_quietly().await?;

To mute model events across multiple operations, wrap the async block in model::without_events. Model hooks still execute inside the block, so derived fields such as slugs are still populated:

1use laravel::model::{self, create};
2 
3model::without_events(async {
4 create!(User { name: "Taylor", email: "[email protected]", password: "secret" }).await?;
5 create!(User { name: "Abigail", email: "[email protected]", password: "secret" }).await?;
6 
7 Ok::<_, laravel::Error>(())
8})
9.await?;
1use laravel::model::{self, create};
2 
3model::without_events(async {
4 create!(User { name: "Taylor", email: "[email protected]", password: "secret" }).await?;
5 create!(User { name: "Abigail", email: "[email protected]", password: "secret" }).await?;
6 
7 Ok::<_, laravel::Error>(())
8})
9.await?;

Which writes run hooks and events

Hooks and events run only for writes that operate on model instances. Bulk query writes, insert, and upsert modify rows directly in SQL without hydrating models, so they skip both:

Write Hooks Event
create!, create, lists, related models, and creates through a relationship creating for each row Created for each row
first_or_create and update_or_create creating on insert, updating on update Created on insert, Updated on update
update!, update, increment, and decrement updating Updated
delete and destroy deleting Deleted for each model
insert, upsert, update_values, and update!, update, and delete on a query None None

Testing

In your tests, seed records with factories, exercise your routes, and verify database state with the database assertions. Enable refresh_database so every test runs against a clean migrated schema:

1// tests/posts.rs
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn users_can_delete_their_posts(app: Application) -> laravel::Result<()> {
8 let user = User::factory().create().await?;
9 let post = Post::factory().for_(Post::user, &user).create().await?;
10 
11 app.delete(&format!("/posts/{}", post.id)).acting_as(&user).await.assert_redirect();
12 
13 app.assert_model_missing(&post).await;
14 
15 Ok(())
16}
1// tests/posts.rs
2use laravel::testing::prelude::*;
3 
4use app::models::{Post, User};
5 
6#[laravel::test]
7async fn users_can_delete_their_posts(app: Application) -> laravel::Result<()> {
8 let user = User::factory().create().await?;
9 let post = Post::factory().for_(Post::user, &user).create().await?;
10 
11 app.delete(&format!("/posts/{}", post.id)).acting_as(&user).await.assert_redirect();
12 
13 app.assert_model_missing(&post).await;
14 
15 Ok(())
16}

Because auto-increment sequences continue incrementing across tests, assert against the keys returned by the models you created rather than hard-coded IDs like 1.

To learn more about database assertions, refreshing and seeding test databases, and testing model events, check out the testing guide's database testing section.