# Database: Models
- [Introduction](#introduction)
- [Declaring models](#declaring-models)
- [Table and column names](#table-and-column-names)
- [Primary keys](#primary-keys)
- [Defining fields](#defining-fields)
- [Timestamps](#timestamps)
- [Enum columns](#enum-columns)
- [JSON columns](#json-columns)
- [Values over several columns](#values-over-several-columns)
- [Retrieving models](#retrieving-models)
- [Filtering with typed columns](#filtering-with-typed-columns)
- [Aggregates](#aggregates)
- [Comparing with subqueries](#comparing-with-subqueries)
- [Paginating results](#paginating-results)
- [Scopes](#scopes)
- [Chunking and streaming](#chunking-and-streaming)
- [Ordering results](#ordering-results)
- [Comparing models](#comparing-models)
- [Route model binding](#route-model-binding)
- [Customizing the key](#customizing-the-key)
- [Nested models](#nested-models)
- [Creating models](#creating-models)
- [Fill structs](#fill-structs)
- [Required columns](#required-columns)
- [Creating related models together](#creating-related-models-together)
- [Building a create in steps](#building-a-create-in-steps)
- [Finding or creating models](#finding-or-creating-models)
- [Inserting many rows](#inserting-many-rows)
- [Replicating models](#replicating-models)
- [Updating models](#updating-models)
- [Updating only the fields a request sends](#updating-only-the-fields-a-request-sends)
- [Incrementing a column](#incrementing-a-column)
- [Building an update in steps](#building-an-update-in-steps)
- [Updating many rows](#updating-many-rows)
- [Reloading from the database](#reloading-from-the-database)
- [Deleting models](#deleting-models)
- [Serializing models](#serializing-models)
- [Hooks](#hooks)
- [Events](#events)
- [Muting events](#muting-events)
- [Which writes run hooks and events](#which-writes-run-hooks-and-events)
- [Testing](#testing)
<a name="introduction"></a>
## 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](queries.md) used for raw tables, and use the `create!` and `update!` macros to write changes safely.
Before getting started, [configure a database connection](database.md#configuration) and create the model's table with a [migration](migrations.md). Models live in `src/models/`, one file per model, alongside the included `User` model:
```rust
// src/models/post.rs
use laravel::model::{BelongsTo, model};
use laravel::time::Timestamp;
use crate::models::User;
#[model]
pub struct Post {
pub id: i64,
pub user_id: i64,
pub title: String,
pub body: Option<String>,
#[default]
pub votes: i64,
#[default]
pub views: i64,
pub published_at: Option<Timestamp>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
#[belongs_to]
pub user: BelongsTo<User>,
}
```
`#[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](model-relationships.md#belongs-to) to the user who authored the post.
You can query a model directly from a route handler:
```rust
use laravel::inertia::{self, Page, props};
use crate::models::Post;
pub async fn index() -> laravel::Result<Page> {
let posts = Post::query()
.filter(Post::votes.gt(100) & Post::published_at.is_not_null())
.order_by(Post::published_at.desc())
.get()
.await?;
Ok(inertia::render("Posts/Index", props! { posts }))
}
```
`Post::votes` and `Post::published_at` are [typed columns](#filtering-with-typed-columns). Because each column carries its Rust type, comparing `Post::votes` against a string fails at compile time rather than failing at runtime.
<a name="declaring-models"></a>
## Declaring models
Apply `#[model]` to a struct with named [fields](#defining-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](#serializing-models).
<a name="table-and-column-names"></a>
### 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")]` |
```rust
use laravel::model::model;
use laravel::str::Uuid;
#[model(table = "people", connection = "directory", route_key = "slug")]
pub struct Person {
#[key]
pub uuid: Uuid,
pub slug: String,
#[column("is_admin")]
pub admin: bool,
}
```
`#[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")]`.
<a name="primary-keys"></a>
### 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 |
<a name="defining-fields"></a>
### 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:
```rust
use std::net::IpAddr;
use laravel::model::model;
use laravel::numeric::Decimal;
use laravel::str::Uuid;
use laravel::time::{Timestamp, civil::Date};
#[model]
pub struct Invoice {
pub id: Uuid,
pub number: String,
pub subtotal: Decimal,
#[default]
pub paid: bool,
pub due_on: Option<Date>,
pub billed_from: Option<IpAddr>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
```
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](database.md#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](#json-columns) |
| `#[derive(Enum)]` | Prelude | [Enum columns](#enum-columns) |
| `Vector` | `laravel::db::Vector` | Vector embeddings (`pgvector` / MariaDB) |
| `Encrypted<T>` | `laravel::crypt::Encrypted` | [Encrypted columns](encryption.md#encrypting-model-columns) |
| `PasswordHash` | `laravel::hash::PasswordHash` | Hashed passwords |
| `RememberToken` | `laravel::auth::RememberToken` | Authentication remember tokens |
<a name="timestamps"></a>
### Timestamps
If your model defines `created_at` and `updated_at` fields (as `Timestamp` or `Option<Timestamp>` to match [`table.timestamps()`](schema.md#column-types)), 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](database.md#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.md) queries do not set timestamps automatically, so supply them explicitly when needed.
<a name="enum-columns"></a>
### 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")]`):
```rust
// src/models/customer.rs
use laravel::prelude::*;
use laravel::model::model;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum Plan {
Free,
Pro,
}
#[model]
pub struct Customer {
pub id: i64,
pub email: String,
pub plan: Plan,
}
```
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`](#json-columns) and store it in a JSON column instead.
<a name="json-columns"></a>
### 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:
```rust
// src/models/user.rs
use laravel::db;
use laravel::model::model;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Json)]
pub struct Preferences {
pub theme: String,
pub notifications: bool,
}
#[model]
pub struct User {
pub id: i64,
pub email: String,
pub preferences: Preferences,
}
```
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](#creating-related-models-together):
```rust
use laravel::model::create;
let preferences = Preferences {
theme: "light".into(),
notifications: true,
};
let mut user = create!(User { email: "taylor@laravel.com", preferences }).await?;
```
To replace the whole JSON value, pass the updated struct to `update!`:
```rust
use laravel::model::update;
let mut preferences = user.preferences.clone();
preferences.theme = "dark".into();
update!(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:
```rust
use laravel::db::values;
user.update_values(values! { "preferences->theme": "dark" }).await?;
User::query()
.filter(User::id.eq(user.id))
.update_values(values! { "preferences->notifications": false })
.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`:
```rust
let dark_mode_users = User::query()
.filter(User::preferences.path("theme").eq("dark"))
.get()
.await?;
let email_subscribers = User::query()
.filter(User::preferences.path("notifications->email").eq(true))
.filter(User::preferences.path("languages[0]").eq("en"))
.get()
.await?;
```
To learn more about JSON path expressions, `json_contains`, and `json_length`, check out the [query builder's JSON columns section](queries.md#json-columns).
<a name="values-over-several-columns"></a>
### 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]`:
```rust
// src/models/order.rs
use laravel::db;
use laravel::model::model;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Embed)]
pub struct Money {
pub amount: i64,
pub currency: String,
}
#[model]
pub struct Order {
pub id: i64,
#[embed]
pub total: Money,
#[embed(prefix = "refunded")]
pub refunded: Money,
}
```
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](#fill-structs), and query updates. Wrap a struct literal in parentheses inside `create!` so it is not parsed as a nested related model:
```rust
use laravel::model::{create, update};
let usd = |amount| Money { amount, currency: "USD".into() };
let mut order = create!(Order {
total: usd(1500),
refunded: (Money { amount: 0, currency: "USD".into() }),
})
.await?;
update!(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`:
```rust
let large_orders = Order::query()
.filter(Order::total.amount.gt(1000))
.get()
.await?;
let currencies = Order::query()
.pluck(Order::total.currency)
.await?;
let price = Money { amount: 1500, currency: "USD".into() };
let matching = Order::query().filter(Order::total.eq(&price)).get().await?;
let 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" }`).
<a name="retrieving-models"></a>
## Retrieving models
Once you have declared a model and migrated its table, you can retrieve all records from the table using `all`:
```rust
use crate::models::Post;
let posts = Post::all().await?;
```
For filtering, ordering, limits, or [pagination](pagination.md), begin a query with `Post::query()`, which wraps the [query builder](queries.md) for the model's table, and finish it with `get`:
```rust
let posts = Post::query()
.filter(Post::published_at.is_not_null())
.order_by(Post::published_at.desc())
.limit(10)
.get()
.await?;
```
To retrieve a single model by its primary key, call `find`, which returns `Option<Post>`:
```rust
let 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):
```rust
use laravel::prelude::*;
use crate::models::Post;
pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<Post>> {
// Returns a 404 response automatically if no post has this ID...
let post = Post::find_or_fail(id).await?;
Ok(Json(post))
}
```
When a model's ID comes directly from a route parameter like this, you'll usually let [route model binding](#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`:
```rust
let 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:
```rust
let post = Post::first_where(Post::title.eq("Hello")).await?;
let post = Post::query()
.filter(Post::votes.gt(100))
.order_by(Post::published_at.desc())
.first()
.await?;
let post = Post::query()
.filter(Post::slug.eq(slug))
.first_or_fail()
.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:
```rust
let users = User::query()
.order_by(User::name)
.limit(10)
.get()
.await?;
let posts = Post::query()
.filter(Post::user_id.is_in(users.keys()))
.get()
.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:
```rust
let titles = Post::query()
.order_by(Post::title)
.pluck(Post::title)
.await?;
let title = Post::query()
.filter(Post::id.eq(1))
.value(Post::title)
.await?;
```
> [!NOTE]
> 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](model-relationships.md#counting-related-rows). To select only a subset of columns into a custom struct, use [`db::table`](queries.md#retrieving-rows) instead.
<a name="filtering-with-typed-columns"></a>
### 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:
```rust
let posts = Post::query()
.filter(Post::user_id.eq(user.id))
.filter(Post::votes.ge(10))
.filter(Post::published_at.is_not_null())
.get()
.await?;
let selected = Post::query()
.filter(Post::id.is_in([1, 2, 3]))
.filter(Post::title.ne("Draft"))
.get()
.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 `!`:
```rust
let posts = Post::query()
.filter(Post::title.starts_with("Laravel") & Post::votes.ge(10))
.filter(Post::updated_at.gt(Post::created_at))
.order_by(Post::votes.desc())
.get()
.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](#comparing-with-subqueries) 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](queries.md#dates) |
| `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!`:
```rust
use laravel::db;
let posts = Post::query()
.filter(Post::votes.gt(100) & db::raw!("extract(dow from created_at) = 1"))
.get()
.await?;
```
<a name="aggregates"></a>
### Aggregates
Model queries support the same aggregate methods as [`db::table`](queries.md#aggregates), including `count`, `exists`, `sum`, `avg`, `min`, and `max`:
```rust
let published = Post::query()
.filter(Post::published_at.is_not_null())
.count()
.await?;
let has_drafts = Post::query()
.filter(Post::published_at.is_null())
.exists()
.await?;
let total_votes: Option<i64> = Post::query().sum(Post::votes).await?;
let average_votes: Option<f64> = Post::query().avg(Post::votes).await?;
let top_votes: Option<i64> = Post::query().max(Post::votes).await?;
```
<a name="comparing-with-subqueries"></a>
### 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:
```rust
let commented = Comment::query()
.join("posts", Post::id.eq(Comment::post_id))
.filter(Post::featured.eq(true))
.select_column(Comment::user_id);
let posts = Post::query()
.filter(Post::user_id.is_in(commented))
.get()
.await?;
let average = Post::query().select_column(Post::votes.avg());
let popular = Post::query()
.filter(Post::votes.gt(average))
.get()
.await?;
```
You may pass any typed column, column aggregate (`count`, `count_distinct`, `sum`, `avg`, `min`, `max`), or `db::table` query selecting a single column.
<a name="paginating-results"></a>
### 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:
```rust
let posts = Post::query()
.filter(Post::published_at.is_not_null())
.order_by(Post::published_at.desc())
.paginate(15)
.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](pagination.md).
<a name="scopes"></a>
### 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`:
```rust
use laravel::db::Condition;
impl Post {
pub fn popular() -> Condition {
Post::votes.gt(100)
}
pub fn is_published() -> Condition {
Post::published_at.is_not_null()
}
}
let posts = Post::query()
.filter(Post::popular() & Post::is_published())
.get()
.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:
```rust
impl Post {
pub fn by(user: &User) -> Condition {
Post::user_id.eq(user.id)
}
}
let posts = Post::query()
.filter(Post::by(&user) & Post::is_published())
.get()
.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`:
```rust
use laravel::db::Builder;
impl Post {
pub fn trending(query: Builder<Post>) -> Builder<Post> {
query.filter(Post::votes.gt(10)).order_by(Post::votes.desc()).limit(10)
}
}
let posts = Post::query()
.filter(Post::is_published())
.scope(Post::trending)
.get()
.await?;
```
<a name="chunking-and-streaming"></a>
### 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:
```rust
use laravel::stream::TryStreamExt;
let mut pages = Post::query().filter(Post::votes.eq(0)).chunk_by_id(100);
while let Some(posts) = pages.try_next().await? {
for post in posts {
post.delete().await?;
}
}
```
`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](model-relationships.md#eager-loading) requested with `with` for each page. By contrast, `cursor` streams individual rows over a single query and therefore cannot eager-load relationships.
<a name="ordering-results"></a>
### 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:
```rust
let posts = Post::query()
.order_by(Post::votes.desc())
.order_by(Post::title)
.get()
.await?;
```
For sorting by a timestamp column, `latest` orders newest first and `oldest` orders oldest first:
```rust
let 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:
```rust
// src/models/ticket.rs
use laravel::prelude::*;
use laravel::model::model;
use laravel::time::Timestamp;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
Low,
Medium,
High,
Urgent,
}
#[model]
pub struct Ticket {
pub id: i64,
pub priority: Priority,
pub created_at: Timestamp,
}
```
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:
```rust
use crate::models::{Priority, Ticket};
let tickets = Ticket::query()
.in_order_of(Ticket::priority, [Priority::Urgent, Priority::High])
.order_by(Ticket::created_at)
.get()
.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.
<a name="comparing-models"></a>
### 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:
```rust
let post = Post::query()
.with(Post::user)
.with(Post::comments.with(Comment::user))
.find_or_fail(id)
.await?;
for comment in &post.comments {
let from_author = comment.user.is(&post.user);
}
```
`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`).
<a name="route-model-binding"></a>
## 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`:
```rust
// src/routes/web.rs
route.get("/posts/{post}", posts::show);
```
```rust
use laravel::inertia::{self, Page, props};
use crate::models::Post;
pub async fn show(post: Post) -> Page {
inertia::render("Posts/Show", props! { post })
}
```
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:
```rust
// "/posts/42", or "/posts/hello-world" with route_key = "slug"
Ok(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?`.
<a name="customizing-the-key"></a>
### 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:
```rust
// src/routes/web.rs
route.get("/blog/{post:slug}", blog::show);
route.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:
```rust
route!(blog::show, &post)?; // "http://localhost/blog/hello-world"
route!(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](#table-and-column-names).
<a name="nested-models"></a>
### 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](#customizing-the-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`:
```rust
route.get("/users/{user}/blog/{post:slug}", blog::show);
pub async fn show(user: User, post: Post) -> Page {
inertia::render("Posts/Show", props! { user, post })
}
```
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!`](routing.md#nested-resources):
```rust
route.get("/users/{user}/posts/{post}", posts::show).scope_bindings();
resource!(users::posts).scope_bindings();
```
To enable scoped bindings for an entire group of routes, call `scope_bindings` before `group`:
```rust
route.scope_bindings().group(|route| {
route.get("/users/{user}/posts/{post}", posts::show);
route.get("/teams/{team}/members/{user}", members::show);
});
```
Laravel resolves the scoped child through a [relationship](model-relationships.md) 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](model-relationships.md#has-many-through). 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](model-relationships.md#has-one-of-many) relationships such as `latest_order` are never used to scope bindings, and [filtered relationships](model-relationships.md#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:
```rust
use laravel::model::{BelongsTo, model};
#[model]
pub struct Post {
pub id: i64,
pub author_id: i64,
pub title: String,
#[belongs_to]
pub author: BelongsTo<User>,
}
```
```rust
route.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:
```rust
route.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.
<a name="creating-models"></a>
## Creating models
`create!` inserts a row and returns the stored model populated with its generated key, [timestamps](#timestamps), and database defaults. This handler creates a post for the logged-in user:
```rust
use laravel::model::create;
use laravel::prelude::*;
use crate::models::{Post, User};
pub async fn store(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
let post = create!(Post { title: "My first post", user: &user }).await?;
Ok(redirect!(posts::show, &post))
}
```
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](model-relationships.md#belongs-to) 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`](hashing.md#password-fields) for `PasswordHash`, which Laravel hashes with [`hash::make`](hashing.md) before storing. If a value does not match the column, the compiler error lists the accepted types.
<a name="fill-structs"></a>
### 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`](validation.md), and `Fill`, then spread `..input` at the end of `create!`:
```rust
use laravel::model::create;
use laravel::prelude::*;
use crate::models::{Post, User};
#[laravel::input(fills = Post)]
#[validate(authenticated)]
pub struct NewPost {
#[validate(required, max_length(255))]
pub title: String,
#[validate(required)]
pub body: String,
}
pub async fn store(
Authenticated(user): Authenticated<User>,
Valid(input): Valid<NewPost>,
) -> laravel::Result<Redirect> {
let post = create!(Post { user: &user, ..input }).await?;
Ok(redirect!(posts::show, &post))
}
```
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](model-relationships.md#belongs-to-many):
```rust
use crate::models::Tag;
#[laravel::input(fills = Post)]
#[validate(authenticated)]
pub struct NewPost {
#[validate(required, max_length(255))]
pub title: String,
#[fill(skip)]
#[serde(default)]
#[validate(max_items(10), each(exists(Tag::id)))]
pub tag_ids: Vec<i64>,
}
pub async fn store(
Authenticated(user): Authenticated<User>,
Valid(input): Valid<NewPost>,
) -> laravel::Result<Redirect> {
let post = create!(Post { user: &user, ..&input }).await?;
post.tags().attach(&input.tag_ids).await?;
Ok(redirect!(posts::show, &post))
}
```
`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](#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](validation.md#validation-quickstart).
<a name="fill-structs-outside-a-request"></a>
#### 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`](validation.md#validating-outside-a-request):
```rust
use laravel::model::{Fill, create};
use laravel::validation::Validate;
use crate::models::{Post, User};
#[derive(Validate, Fill)]
#[fills(Post)]
pub struct PublishPost {
#[validate(required, max_length(255))]
pub title: String,
#[validate(required)]
pub body: String,
}
pub async fn publish(author: &User, input: PublishPost) -> laravel::Result<Post> {
input.validate().await?;
create!(Post {
user: author,
..input
})
.await
}
```
<a name="required-columns"></a>
### 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:
```text
error[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](#hooks), 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`](#finding-or-creating-models).
<a name="creating-related-models-together"></a>
### Creating related models together
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](model-relationships.md#polymorphic-relationships) counterparts afterward:
```rust
use laravel::model::create;
use crate::models::{Post, User};
let post = create!(Post {
title: "Hello",
user: User { name: "Abigail", email: "abigail@laravel.com", password: "secret" },
})
.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:
```rust
let posts = create!([
Post { title: "One", user: &user },
Post { title: "Two", user: &user },
])
.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.
<a name="building-a-create-in-steps"></a>
### 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:
```rust
use laravel::prelude::*;
use crate::models::{Post, User};
pub async fn store(
Authenticated(user): Authenticated<User>,
Valid(input): Valid<NewPost>,
) -> laravel::Result<Redirect> {
let mut create = Post::create().user(&user).fill(input);
if user.email_verified_at.is_some() {
create = create.published_at(laravel::now());
}
let post = create.await?;
Ok(redirect!(posts::show, &post))
}
```
<a name="finding-or-creating-models"></a>
### 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`:
```rust
use laravel::model::create;
use crate::models::User;
let user = User::first_or_create(
User::email.eq(email),
create!(User { name, password, .. }),
)
.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:
```rust
let user = User::update_or_create(
User::email.eq("taylor@laravel.com"),
create!(User { name: "Taylor Otwell", password: "secret", .. }),
)
.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)`:
```rust
use laravel::mail;
use laravel::model::FoundOrCreated;
use crate::mail::Welcome;
let user = User::first_or_create(User::email.eq(email), create!(User { name, password, .. }))
.found_or_created()
.await?;
if let FoundOrCreated::Created(user) = &user {
mail::to(user).queue(Welcome::new(user)?).await?;
}
let 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.
<a name="inserting-many-rows"></a>
### 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](#fill-structs)) to write all rows in a single SQL statement and return the number of inserted rows:
```rust
use laravel::model::row;
use crate::models::User;
let inserted = User::insert(row!([
User { email: "taylor@laravel.com", name: "Taylor", password: "secret" },
User { email: "abigail@laravel.com", name: "Abigail", password: "secret" },
]))
.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:
```rust
let rows = imports.into_iter().map(|item| {
row!(User {
email: item.email,
name: item.name,
password: item.password,
})
});
let 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.
<a name="upserts"></a>
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:
```rust
let rows = row!([
User { email: "taylor@laravel.com", name: "Taylor Otwell", password: "secret" },
User { email: "jess@laravel.com", name: "Jess", password: "secret" },
]);
let 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:
```rust
// Same column types (`i64` and `i64`): pass an array...
Post::upsert(posts, [Post::id], [Post::votes, Post::views]).await?;
// Mixed column types (`String` and `Option<Timestamp>`): pass a tuple...
User::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`](queries.md#upserts).
Because `insert` and `upsert` write rows without hydrating models, they do not run [hooks](#hooks), dispatch [events](#events), or create nested related models (pass an existing parent such as `user: &user` instead).
<a name="replicating-models"></a>
### 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:
```rust
use laravel::model::create;
use crate::models::Address;
let shipping = create!(Address {
kind: "shipping",
line_1: "123 Example Street",
city: "Victorville",
state: "CA",
postcode: "90001",
})
.await?;
let 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](model-relationships.md#loading-into-models-you-already-have) 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:
```rust
use laravel::model::create;
use laravel::prelude::*;
use crate::models::Flight;
pub async fn duplicate(flight: Flight) -> laravel::Result<Redirect> {
let copy = create!(Flight {
..flight.replicate().except((Flight::last_flown_at, Flight::last_pilot_id))
})
.await?;
Ok(redirect!(flights::show, ©))
}
```
<a name="updating-models"></a>
## 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](#route-model-binding) and updates it from a validated form:
```rust
use laravel::model::update;
use laravel::prelude::*;
use crate::models::Post;
#[laravel::input(fills = Post)]
#[validate(anyone)]
pub struct EditPost {
#[validate(required, max_length(255))]
pub title: String,
}
pub async fn update(
mut post: Post,
Valid(input): Valid<EditPost>,
) -> laravel::Result<Redirect> {
update!(post { published_at: laravel::now(), ..input }).await?;
Ok(redirect!(posts::show, &post))
}
```
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-many-rows).
<a name="updating-only-the-fields-a-request-sends"></a>
### 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:
```rust
use laravel::model::update;
use laravel::prelude::*;
use laravel::validation::Sometimes;
use crate::models::User;
#[laravel::input(fills = User)]
#[validate(authenticated)]
pub struct EditProfile {
#[validate(required, max_length(255))]
pub name: Sometimes<String>,
#[validate(max_length(1000))]
pub bio: Sometimes<Option<String>>,
}
pub async fn update(
Authenticated(mut user): Authenticated<User>,
Valid(input): Valid<EditProfile>,
) -> laravel::Result<Redirect> {
update!(user { ..input }).await?;
Ok(Redirect::back())
}
```
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](validation.md#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.
<a name="incrementing-a-column"></a>
### 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:
```rust
update!(post { views += 1 }).await?;
update!(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.
<a name="building-an-update-in-steps"></a>
### 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:
```rust
use laravel::time::Timestamp;
let mut update = post.update().fill(&input);
if input.draft {
update = update.published_at(None::<Timestamp>);
}
update.await?;
```
Because an `Option` column's setter accepts multiple optional types, annotate `None` with its inner type (such as `None::<Timestamp>`).
<a name="updating-many-rows"></a>
### 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:
```rust
use laravel::model::update;
use laravel::prelude::*;
use crate::models::{Post, User};
pub async fn publish_drafts(
Authenticated(user): Authenticated<User>,
) -> laravel::Result<Redirect> {
update!(user.posts().filter(Post::published_at.is_null()) {
published_at: laravel::now(),
})
.await?;
Ok(Redirect::back())
}
```
`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:
```rust
update!(Post::query().filter(Post::user_id.eq(old_author.id)) {
user: &new_author,
})
.await?;
update!(Post::query().filter(!Post::published_at.is_null()) {
views += 1,
})
.await?;
```
Because bulk query updates never instantiate models, they do not run [hooks](#hooks) or dispatch [events](#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`:
```rust
update!(post.tags() { featured: true }).await?;
Post::query()
.filter(Post::published_at.is_null())
.update()
.published_at(laravel::now())
.await?;
Post::query()
.filter(!Post::published_at.is_null())
.increment(Post::views, 1)
.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:
```rust
use laravel::db::{col, values};
Post::query()
.filter(Post::votes.gt(100))
.update_values(values! { "options->theme": "dark", score: col("votes") * 2 })
.await?;
```
Models also provide `update_values`, which updates the row and reloads it like [`refresh`](#reloading-from-the-database) so the model reflects database-written columns:
```rust
post.update_values(values! { "options->theme": "dark" }).await?;
```
<a name="reloading-from-the-database"></a>
### 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](model-relationships.md#eager-loading) in place:
```rust
let latest: Option<Post> = post.fresh().await?;
post.refresh().await?;
```
<a name="deleting-models"></a>
## 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:
```rust
post.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](#hooks) and [events](#events) still run, and returns the number of deleted records:
```rust
let 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](#updating-many-rows), skips hooks and events:
```rust
let deleted = Post::query()
.filter(Post::votes.eq(0))
.delete()
.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`](model-relationships.md#attaching-and-syncing-join-rows) 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:
```rust
let deleted = Post::query().oldest(Post::created_at).limit(1000).delete().await?;
```
[Bulk updates](#updating-many-rows) support `order_by` and `limit` as well. For example, this query publishes the ten oldest drafts:
```rust
let drafts = Post::query()
.filter(Post::published_at.is_null())
.oldest(Post::created_at)
.limit(10);
update!(drafts { published_at: laravel::now() }).await?;
```
<a name="serializing-models"></a>
## 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`):
```rust
use laravel::auth::RememberToken;
use laravel::crypt::Encrypted;
use laravel::hash::PasswordHash;
use laravel::model::model;
#[model]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
#[serde(skip)]
pub password: PasswordHash,
#[serde(skip)]
pub remember_token: Option<RememberToken>,
#[serde(skip)]
pub api_secret: Option<Encrypted<String>>,
#[serde(skip)]
pub internal_notes: Option<String>,
}
```
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](cache.md).
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`:
```rust
use laravel::prelude::*;
use serde::Serialize;
use crate::models::User;
#[derive(Serialize)]
pub struct PublicProfile {
pub id: i64,
pub name: String,
}
impl From<User> for PublicProfile {
fn from(user: User) -> Self {
Self {
id: user.id,
name: user.name,
}
}
}
pub async fn show(user: User) -> Json<PublicProfile> {
Json(user.into())
}
```
<a name="hooks"></a>
## 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:
```rust
use laravel::model::{Changes, Draft, Hooks, model};
use laravel::str::Str;
#[model(hooks)]
pub struct Article {
pub id: i64,
pub title: String,
pub slug: String,
pub locked: bool,
}
impl Hooks for Article {
async fn creating(article: &mut Draft<Self>) -> laravel::Result<()> {
if let Some(slug) = article.get(Article::title).map(|title| title.slug()) {
article.set(Article::slug, slug);
}
Ok(())
}
async fn updating(&mut self, changes: &Changes<Self>) -> laravel::Result<()> {
if changes.has(Article::title) {
laravel::abort_if(self.locked, 409)?;
self.slug = self.title.slug();
}
Ok(())
}
async fn deleting(&self) -> laravel::Result<()> {
laravel::abort_if(self.locked, 409)
}
}
```
| 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.
<a name="events"></a>
## Events
After each single-model write, Laravel dispatches a `Created<M>`, `Updated<M>`, or `Deleted<M>` [event](events.md) 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:
```rust
// src/listeners/send_welcome_email.rs
use laravel::event::{Event, listener};
use laravel::model::Created;
use crate::models::User;
#[listener]
async fn send_welcome_email(event: Event<Created<User>>) -> laravel::Result<()> {
let user = &event.model;
// Send the welcome email to user.email...
Ok(())
}
```
Every model event exposes the affected record on `event.model`. Inside a [transaction](database.md#transactions), 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)]`](events.md#running-listeners-in-the-transaction).
`Updated` events also include `event.changes`, detailing which columns changed during the update:
```rust
use laravel::event::{Event, listener};
use laravel::model::Updated;
#[listener]
async fn verify_new_email(event: Event<Updated<User>>) -> laravel::Result<()> {
if event.changes.has(User::email) {
let previous: &str = event.changes.old(User::email);
// Notify the previous address about the change...
}
Ok(())
}
```
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)]`](events.md#queued-listeners). 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](queues.md#models-in-jobs) serialize and reload models using the same key-based lookup.
<a name="muting-events"></a>
### 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()`:
```rust
create!(Post { title: "Hello", user: &user }).quietly().await?;
update!(post { views += 1 }).quietly().await?;
post.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:
```rust
use laravel::model::{self, create};
model::without_events(async {
create!(User { name: "Taylor", email: "taylor@laravel.com", password: "secret" }).await?;
create!(User { name: "Abigail", email: "abigail@laravel.com", password: "secret" }).await?;
Ok::<_, laravel::Error>(())
})
.await?;
```
<a name="which-writes-run-hooks-and-events"></a>
### 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 |
<a name="testing"></a>
## Testing
In your tests, seed records with [factories](factories.md), exercise your routes, and verify database state with the [database assertions](testing.md#database-assertions). Enable [`refresh_database`](testing.md#refreshing-the-database) so every test runs against a clean migrated schema:
```rust
// tests/posts.rs
use laravel::testing::prelude::*;
use app::models::{Post, User};
#[laravel::test]
async fn users_can_delete_their_posts(app: Application) -> laravel::Result<()> {
let user = User::factory().create().await?;
let post = Post::factory().for_(Post::user, &user).create().await?;
app.delete(&format!("/posts/{}", post.id)).acting_as(&user).await.assert_redirect();
app.assert_model_missing(&post).await;
Ok(())
}
```
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](testing.md#testing-the-database).