Database: Models
- Introduction
- Declaring models
- Retrieving models
- Finding a model from a route
- Creating models
- Updating models
- Deleting models
- Models in transactions
- Serializing models
- Hooks
- Events
- Testing
Introduction
Laravel includes a built-in object-relational mapper (ORM) for working with your database using plain Go structs. Each database table has a corresponding model that lets you query, insert, update, and delete records cleanly without writing boilerplate SQL.
A model is a Go struct 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 require no base struct or code generation.
Before getting started, configure your database and create the model's table with a migration. Models live in your application's models package, one file per model, alongside the included User model:
// models/post.go
package models
import "time"
type Post struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Title string `json:"title"`
Body *string `json:"body"`
Votes int64 `json:"votes" db:",default"`
PublishedAt *time.Time `json:"published_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
User *User `json:"user,omitzero" model:"belongs_to"`
}Nullable columns use pointers (*string, *time.Time), which Go reads as nil for NULL. The db:",default" tag marks a column with a database default, allowing you to omit it when creating a record 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. Every model function takes a context.Context carrying your application's database connection, and *web.Request implements context.Context:
package posts
import (
"go.laravel.com/inertia"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Index(r *web.Request) *web.Response {
posts, err := model.Query[models.Post]().
WhereGt("votes", 100).
WhereNotNull("published_at").
Latest("published_at").
Get(r)
if err != nil {
return web.Fail(err)
}
return inertia.Render("Posts/Index", inertia.Props{"posts": posts})
}Get returns a []models.Post. When no rows match, it returns an empty slice rather than nil, so JSON responses serialize as [] instead of null.
Declaring models
A model is a Go struct with an ID field and a field for each column. Each field's Go type determines how its column is read and written, and nullable columns are pointers (*T).
Models serialize to JSON using standard json struct tags. To control which fields appear in JSON and Inertia responses, check out Serializing models.
Table and column names
Laravel infers table and column names by convention, so most models require no overrides:
| Convention | Rule | Override |
|---|---|---|
| Table | The struct's name in snake case, made plural: BlogPost is blog_posts, and Category is categories | Implement TableName() string |
| Column | The field's name in snake case: UserID is user_id, PublishedAt is published_at, and GitHubToken is git_hub_token | db:"is_admin" tag on the field |
| Non-column field | Ignored by the ORM | db:"-", or a model tag for a relationship |
type Person struct {
ID int64 `json:"id"`
Admin bool `json:"admin" db:"is_admin"`
Notes string `json:"-" db:"-"`
}
func (Person) TableName() string {
return "members"
}Primary keys
Laravel determines how new primary keys are generated from the ID field's type and db tag. Most tables use an auto-incrementing int64 key assigned by the database:
| Key field | New keys |
|---|---|
int64, int32, and other integer types | Assigned by the database, such as with the auto-incrementing column created by table.ID() |
uuid.UUID | Create, FirstOrCreate, InsertMany, and Upsert generate a time-ordered version 7 UUID when zero (tag db:",default" to let the database assign one instead) |
string tagged db:",uuid" | Generates a version 7 UUID string when empty |
string tagged db:",ulid" | Generates a 26-character ULID string when empty |
Plain string or custom type | Must be provided explicitly when creating the model |
If you set a uuid.UUID, db:",uuid", or db:",ulid" key yourself before creating the model, Laravel preserves your value. A custom key type that implements encoding.TextUnmarshaler (such as uuid.UUID) lets model.FromRoute parse it from route parameters.
Defining fields
Each field on a model struct corresponds to a column in its database table. Use pointers (*T) for nullable columns, and tag columns that have a database default value with db:",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:
// models/invoice.go
package models
import (
"net/netip"
"time"
"uuid"
"go.laravel.com/date"
"go.laravel.com/numeric"
)
type Invoice struct {
ID uuid.UUID `json:"id"`
Number string `json:"number"`
Subtotal numeric.Decimal `json:"subtotal"`
Paid bool `json:"paid" db:",default"`
DueOn *date.Date `json:"due_on"`
BilledFrom *netip.Addr `json:"billed_from"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}Laravel supports the following field types out of the box (any of them may be a pointer *T for nullable columns):
| Go type | Import | Column kind |
|---|---|---|
int64, int32, and other integer types | Built-in | Signed and unsigned integers |
float32, float64 | Built-in | Floating-point numbers |
numeric.Decimal | go.laravel.com/numeric | Exact decimals (money, rates) |
bool | Built-in | Booleans |
string, or a custom string type | Built-in | Text / VARCHAR, and enum columns |
[]byte | Built-in | Binary / BLOB / BYTEA |
time.Time | time | Timestamps (TIMESTAMPTZ / TIMESTAMP) |
date.Date | go.laravel.com/date | Calendar dates |
uuid.UUID | uuid | UUIDs |
netip.Addr | net/netip | IP addresses |
db.JSON[T] | go.laravel.com/db | JSON columns |
db.Vector | go.laravel.com/db | Vector embeddings (pgvector / MariaDB) |
crypt.Encrypted[T] | go.laravel.com/crypt | Encrypted columns |
Custom types that implement driver.Valuer and sql.Scanner also work directly as model fields. When several models share columns such as CreatedAt and UpdatedAt, you may group them into an embedded struct; its fields map to columns as if declared directly on the model.
Database defaults
By default, model.Create writes every column, including fields left at their zero value. When a column has a database default (such as a status column defaulting to 'draft'), writing Go's zero value would overwrite the default with "".
Tag those fields with db:",default". When a tagged field holds its zero value, model.Create omits the column from the INSERT so the database default applies, then reads the stored value back into the struct:
type Order struct {
ID int64 `json:"id"`
Status string `json:"status" db:",default"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}Setting the field explicitly (such as Order{Status: "paid"}) writes your value instead. You may combine default with a custom column name, as in db:"state,default".
Because Go cannot distinguish an explicit zero value from an omitted field, use a pointer when you need to write a zero value to a defaulted column (such as Active *bool when active defaults to true): nil uses the database default, while a pointer to false writes false.
Timestamps
If your model defines CreatedAt and UpdatedAt fields (as time.Time or *time.Time to match table.Timestamps()), Laravel populates both automatically on model.Create and refreshes UpdatedAt on every update. If you explicitly set a timestamp before creating a model, Laravel preserves your value, which is useful when importing historical records.
Model query methods (Update, Increment, and Decrement) also maintain updated_at. Raw db.Table queries do not set timestamps automatically, so supply them explicitly when needed.
Enum columns
To store an enum in a text column, define a string type with constants for each variant. Named string types read and write directly as text without extra methods:
// models/customer.go
package models
type Plan string
const (
Free Plan = "free"
Pro Plan = "pro"
)
type Customer struct {
ID int64 `json:"id"`
Email string `json:"email"`
Plan Plan `json:"plan"`
}Enum fields work directly with queries and writes, such as WhereEq("plan", models.Pro) and db.Values{"plan": models.Pro}. To store a structured value that carries additional fields, use a JSON column instead.
JSON columns
When a column stores structured JSON data, such as user preferences or integration settings, define a struct for the shape and wrap it in db.JSON[T]. Back the column with table.JSON or table.JSONB in your migration:
// models/user.go
type Preferences struct {
Theme string `json:"theme"`
Notifications bool `json:"notifications"`
}
type User struct {
ID int64 `json:"id"`
Email string `json:"email"`
Preferences db.JSON[Preferences] `json:"preferences"`
}model.Create serializes the value as JSON, and reading the model decodes it into user.Preferences.V. To update a single nested key in place without replacing the entire JSON document, use arrow notation (column->key) in model.Update. Calling model.Update writes the change in SQL and reloads the column on the struct, while calling Update on a query updates all matching rows in a single statement:
err := model.Update(r, &user, db.Values{"preferences->theme": "dark"})
_, err = model.Query[models.User]().
WhereEq("id", user.ID).
Update(r, db.Values{"preferences->notifications": false})You can also filter models by JSON keys using the same arrow notation:
darkModeUsers, err := model.Query[models.User]().
WhereEq("preferences->theme", "dark").
Get(r)To learn more about JSON path expressions, WhereJSONContains, and WhereJSONLength, 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, define a struct holding those columns and tag the model field with db:",embed":
// models/order.go
type Money struct {
Amount int64 `json:"amount"`
Currency string `json:"currency"`
}
type Order struct {
ID int64 `json:"id"`
Total Money `json:"total" db:",embed"`
Refunded Money `json:"refunded" db:"refund,embed"`
}By default, Laravel prefixes each embedded column with the model field's column name, so Total maps to total_amount and total_currency, and Refunded (tagged db:"refund,embed") maps to refund_amount and refund_currency. To use the embedded struct's column names without a prefix, embed it anonymously (struct { ID int64; Money }).
Passing a Money value populates all of its underlying columns across model.Create, model.Update, and WhereEq, while individual sub-columns can be filtered, ordered, or plucked directly by name:
order := models.Order{Total: models.Money{Amount: 1500, Currency: "USD"}}
err := model.Create(r, &order)
err = model.Update(r, &order, db.Values{"refund": models.Money{Amount: 500, Currency: "USD"}})
matching, err := model.Query[models.Order]().WhereEq("total", order.Total).Get(r)
large, err := model.Query[models.Order]().WhereGt("total_amount", 1000).Get(r)JSON serialization represents embedded fields as nested objects (such as "total": {"amount": 1500, "currency": "USD"}). The db:",embed" tag works with db.Table queries as well.
Retrieving models
Once you have declared a model and migrated its table, you can retrieve all records from the table using model.Query and Get:
posts, err := model.Query[models.Post]().Get(r)For filtering, ordering, limits, or pagination, chain query builder clauses before calling Get:
posts, err := model.Query[models.Post]().
WhereNotNull("published_at").
Latest("published_at").
Limit(10).
Get(r)To retrieve a single model by its primary key, call model.Find. If no row matches, Find returns a *db.NotFoundError, which web.Fail turns into a 404 response automatically:
package posts
import (
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Show(r *web.Request) *web.Response {
post, err := model.Find[models.Post](r, r.PathValue("post"))
if err != nil {
return web.Fail(err)
}
return web.JSON(post)
}When a model's key comes from a route parameter, you will usually use model.FromRoute instead, which also returns a 404 when a parameter fails to parse (such as /posts/hello). To handle a missing row yourself, check db.IsNotFound(err), which matches both *db.NotFoundError and sql.ErrNoRows.
To retrieve several models by their IDs in a single query, pass the IDs to FindMany. It returns the matching models in the query's order and skips any ID with no row:
posts, err := model.Query[models.Post]().OrderBy("title").FindMany(r, form.PostIDs)To retrieve the first model matching a query, call First (returning *db.NotFoundError when no row matches). When a query must match exactly one row, call Sole instead, which also returns *db.MultipleRowsError if more than one row matches:
post, err := model.Query[models.Post]().
WhereGt("votes", 100).
Latest("published_at").
First(r)
post, err = model.Query[models.Post]().WhereEq("slug", slug).Sole(r)To extract the primary keys from a slice of models, pass the slice to model.Keys:
users, err := model.Query[models.User]().OrderBy("name").Limit(10).Get(r)
if err != nil {
return web.Fail(err)
}
posts, err := model.Query[models.Post]().WhereIn("user_id", model.Keys(users)).Get(r)To retrieve a single column without loading full models, call Pluck for a slice of values or Value for the first matching row's value:
titles, err := model.Query[models.Post]().OrderBy("title").Pluck[string](r, "title")
title, err := model.Query[models.Post]().WhereEq("id", 1).Value[string](r, "title")说明
Model queries select every column to populate the struct. To include computed values from related rows (such as each post's comment count), use WithCount and the other relationship aggregates. To select a subset of columns into a custom struct, use db.Table instead.
Filtering models
Use the operator helpers (WhereEq, WhereNe, WhereLt, WhereLe, WhereGt, WhereGe) or Where with an explicit operator to narrow results. Each clause you chain combines with AND:
posts, err := model.Query[models.Post]().
WhereEq("user_id", user.ID).
WhereGe("votes", 10).
WhereNotNull("published_at").
Get(r)Model queries support the same conditions as the query builder:
| Method | Matches models where the column |
|---|---|
WhereEq, WhereNe, WhereLt, WhereLe, WhereGt, WhereGe | Compares with value using =, <>, <, <=, >, or >= |
Where(column, operator, value) | Compares with value using =, <>, <, <=, >, >=, like, or not like |
WhereIn(column, values), WhereNotIn | Is (or isn't) in a slice or subquery; an empty slice matches no rows |
WhereBetween(column, low, high) | Falls between two values |
WhereNull(column), WhereNotNull | Is (or isn't) NULL |
WhereLike(column, pattern, caseSensitive) | Matches a like pattern (OrWhereLike, WhereNotLike, and OrWhereNotLike are also available) |
WhereColumn(first, operator, second) | Compares with another column on the same row |
WherePast(column), WhereFuture | Is before (or after) the current time |
WhereToday(column), WhereBeforeToday, WhereAfterToday | Falls on, before, or after today in UTC |
Use OrWhere (and OrWhereEq, OrWhereGt, and so on) to join conditions with OR, and WhereGroup to wrap grouped conditions in parentheses:
posts, err := model.Query[models.Post]().
WhereNotNull("published_at").
WhereGroup(func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
return q.WhereGt("votes", 100).OrWhereEq("user_id", user.ID)
}).
Get(r)Laravel validates every column name against the model's schema when you build the query and panics immediately on a typo:
model: Post has no column "vots": its columns are id, user_id, title, body, votes, published_at, created_at, updated_atBecause an unknown column panics, always validate user-supplied column names (such as sort parameters) against an allow-list before passing them to a query clause.
To filter by a joined table, prefix its columns with the table name. Unprefixed columns refer to the model's table:
posts, err := model.Query[models.Post]().
Join("users", "users.id", "=", "user_id").
WhereEq("users.active", true).
Get(r)For database-specific expressions that aren't covered by query methods, use WhereRaw (which skips column validation):
posts, err := model.Query[models.Post]().
WhereGt("votes", 100).
WhereRaw("extract(dow from created_at) = ?", 1).
Get(r)Model queries are immutable values: each clause returns a new builder without modifying the original, so you can store a base query in a variable and derive multiple queries from it.
Aggregates
Model queries expose the same aggregate methods as db.Table queries: Count, CountDistinct, Exists, Sum, Avg, Min, and Max. Sum, Avg, Min, and Max take their result type as a type argument:
published, err := model.Query[models.Post]().WhereNotNull("published_at").Count(r)
hasDrafts, err := model.Query[models.Post]().WhereNull("published_at").Exists(r)
totalVotes, err := model.Query[models.Post]().Sum[int64](r, "votes")
averageVotes, err := model.Query[models.Post]().Avg[*float64](r, "votes")
topVotes, err := model.Query[models.Post]().Max[*int64](r, "votes")Sum returns 0 when no rows match. Because SQL returns NULL for Avg, Min, and Max on an empty set, request a pointer type (such as *float64 or *int64) when the query may match zero rows.
Comparing with subqueries
When a filter depends on values from another table or an aggregate across rows, call Select on a model query (or a db.Table query) and pass it directly to WhereIn or Where so the database evaluates it as a subquery in a single statement:
banned := model.Query[models.User]().WhereEq("banned", true).Select("id")
posts, err := model.Query[models.Post]().WhereIn("user_id", banned).Get(r)
average := db.Table("posts").SelectRaw("avg(votes)")
popular, err := model.Query[models.Post]().WhereGt("votes", average).Get(r)Select validates its column names against the model's fields just like every other clause.
Paginating results
For long lists of models, replace Get with Paginate to return one page of records along with pagination metadata. r.Page reads the current page number from the request:
posts, err := model.Query[models.Post]().
WhereNotNull("published_at").
Latest("published_at").
Paginate(r, r.Page(15))You may also use SimplePaginate for previous and next links without a total row count, or CursorPaginate for large datasets. To learn more about rendering pagination links and customizing URLs, check out the pagination guide.
Scopes
Scopes let you encapsulate reusable query constraints as plain functions alongside your model and apply them with Scope:
// models/post.go
func Popular(q *model.Builder[Post]) *model.Builder[Post] {
return q.WhereGt("votes", 100)
}
func Published(q *model.Builder[Post]) *model.Builder[Post] {
return q.WhereNotNull("published_at")
}posts, err := model.Query[models.Post]().
Scope(models.Popular).
Scope(models.Published).
Latest("published_at").
Get(r)For parameterized scopes, return a scope function:
func By(userID int64) func(*model.Builder[Post]) *model.Builder[Post] {
return func(q *model.Builder[Post]) *model.Builder[Post] {
return q.WhereEq("user_id", userID)
}
}To apply a clause conditionally based on runtime input, use When:
posts, err := model.Query[models.Post]().
When(search != "", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
return q.WhereLike("title", "%"+search+"%", false)
}).
Get(r)Chunking and streaming
When processing thousands of rows in a console command or background job, load records in batches rather than holding the entire table in memory. ChunkByID walks the table in pages ordered by primary key, so you can safely update or delete rows while iterating:
func DeleteUnvotedPosts(ctx context.Context) error {
unvoted := model.Query[models.Post]().WhereEq("votes", 0)
for posts, err := range unvoted.ChunkByID(ctx, 100) {
if err != nil {
return err
}
for _, post := range posts {
if err := model.Delete(ctx, &post); err != nil {
return err
}
}
}
return nil
}LazyByID fetches the same pages behind the scenes while yielding one model at a time (for post, err := range unvoted.LazyByID(ctx, 100)). ChunkByIDDesc and LazyByIDDesc walk primary keys in descending order.
Chunk pages using the query's own OrderBy and OFFSET, which is useful for read-only passes in a custom order; avoid it when mutating or deleting rows that affect the query's filter or order. Chunk, ChunkByID, and LazyByID all support eager loading.
Cursor executes a single query and streams one model at a time without buffering pages. It does not eager-load relationships and holds the database cursor open until iteration finishes, so keep work inside the loop brief.
Ordering results
Use OrderBy for ascending order and OrderByDesc for descending order. Chained calls break ties in order:
posts, err := model.Query[models.Post]().
OrderByDesc("votes").
OrderBy("title").
Get(r)Latest and Oldest sort by a timestamp column in descending or ascending order:
posts, err := model.Query[models.Post]().Latest("created_at").Limit(10).Get(r)To order models by a value from another table (such as sorting users by their most recent login), pass a scalar db.Table subquery to OrderBySub or OrderBySubDesc:
lastLogin := db.Table("logins").
SelectRaw("max(created_at)").
WhereColumn("logins.user_id", "=", "users.id")
users, err := model.Query[models.User]().OrderBySubDesc(lastLogin).Get(r)To sort by a relationship count, check out ordering by a relationship count.
To sort rows in a custom domain order rather than alphabetically or numerically (such as urgent support tickets before high-priority tickets), use InOrderOf. Rows whose value isn't in the list appear last:
// models/ticket.go
package models
import "time"
type Priority string
const (
Low Priority = "low"
Medium Priority = "medium"
High Priority = "high"
Urgent Priority = "urgent"
)
type Ticket struct {
ID int64 `json:"id"`
Priority Priority `json:"priority"`
CreatedAt time.Time `json:"created_at"`
}tickets, err := model.Query[models.Ticket]().
InOrderOf("priority", models.Urgent, models.High).
OrderBy("created_at").
Get(r)This returns urgent tickets first, then high-priority tickets, and then low and medium tickets together, ordered oldest first within each group.
Comparing models
To check whether two model instances represent the same database row (such as verifying whether a comment's author also wrote the post), pass pointers to model.Is:
post, err := model.Query[models.Post]().With("user", "comments.user").Find(r, r.PathValue("post"))
if err != nil {
return web.Fail(err)
}
for _, comment := range post.Comments {
fromAuthor := model.Is(comment.User, post.User)
// ...
}model.Is compares primary keys and ignores in-memory field changes, returning false when either pointer is nil or either model has a zero ID. To compare field values in tests, use == or cmp.Diff.
Finding a model from a route
For routes that reference a model by key (such as /posts/{post}), model.FromRoute parses the route parameter and loads the matching record:
// routes/web.go
route.Get("/posts/{post}", posts.Show).Name("posts.show")func Show(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
return inertia.Render("Posts/Show", inertia.Props{"post": post})
}FromRoute parses the parameter into the type of the model's ID field and returns *db.NotFoundError (a 404 response) when parsing fails or no row matches. When you already have a typed key (such as post.UserID), call model.Find directly:
author, err := model.Find[models.User](r, post.UserID)Customizing the key
If every route for a model should resolve by a column other than id (such as slug), implement RouteKeyName() string on the model:
// models/post.go
func (Post) RouteKeyName() string { return "slug" }URL generation respects RouteKeyName automatically when you pass the model:
return web.RedirectRoute("posts.show", "post", &post) // /posts/hello-worldTo bind by another column on a single route while keeping id elsewhere, name the column after a colon in the route path:
// routes/web.go
route.Get("/blog/{post:slug}", posts.Show).Name("blog.show")You can also specify the column explicitly with model.FromRouteBy, or scope the lookup through a model query (returning 404 for records that don't match the query):
post, err := model.FromRouteBy[models.Post](r, "post", "slug")
post, err = model.Query[models.Post]().Scope(models.Published).FromRoute(r, "post")Nested models
For nested routes such as /users/{user}/posts/{post}, resolve the child through the parent's relationship. A request for another user's post returns 404, and two users can each own a post with the same slug:
func Show(r *web.Request) *web.Response {
user, err := model.FromRoute[models.User](r, "user")
if err != nil {
return web.Fail(err)
}
post, err := model.Related[models.Post](&user, "posts").FromRoute(r, "post")
if err != nil {
return web.Fail(err)
}
return inertia.Render("Posts/Show", inertia.Props{"user": user, "post": post})
}This works across belongs_to_many relationships too (such as /teams/{team}/members/{user}), matching only members of that team.
Creating models
model.Create inserts a row and populates the struct with its generated primary key, timestamps, and database defaults:
post := models.Post{Title: "My first post", UserID: user.ID}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", &post)When an insert violates a unique constraint (such as a duplicate email address), db.IsUniqueViolation(err) returns true so you can return a friendly validation error instead of failing the request.
Taking values from a form
When creating models from request input, a client can submit fields your form never rendered. Validate the request into a dedicated form struct and copy only the allowed fields into the model:
package posts
import (
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type StorePost struct {
Title string `json:"title"`
Body string `json:"body"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(255)),
rule.Field(&f.Body, rule.Required),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StorePost]()
if err != nil {
return web.Fail(err)
}
post := models.Post{Title: form.Title, Body: &form.Body}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", &post)
}Never validate request input directly into a model struct, as that would allow clients to populate sensitive columns such as votes or is_admin.
Creating many models
To insert several models in a single transaction, pass a slice to model.CreateMany. Each record runs its hooks, dispatches its events, and receives its generated key; if any insert fails, the transaction rolls back and the slice stays unchanged:
posts := []models.Post{
{Title: "Release notes", UserID: user.ID},
{Title: "Upgrade guide", UserID: user.ID},
}
if err := model.CreateMany(r, posts); err != nil {
return web.Fail(err)
}
// posts[0].ID and posts[1].ID hold the new IDs...For bulk imports or seeders inserting thousands of rows, use model.InsertMany instead. It executes multi-row INSERT statements without reading generated keys back, and skips hooks and events.
To create models through a relationship, check out creating related models.
Finding or creating models
To retrieve a record matching a set of attributes or create it if no matching row exists, call model.FirstOrCreate. Pass the lookup attributes first and any additional attributes for new rows second (or nil if none are needed):
// models/tag.go
type Tag struct {
ID int64 `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}tag, _, err := model.FirstOrCreate[models.Tag](r,
db.Values{"slug": form.Slug},
db.Values{"name": form.Name},
)model.UpdateOrCreate takes the same arguments, updating the existing row with the second set of attributes when a match is found:
tag, _, err := model.UpdateOrCreate[models.Tag](r,
db.Values{"slug": form.Slug},
db.Values{"name": form.Name},
)Both functions return a bool indicating whether a new row was created:
user, created, err := model.FirstOrCreate[models.User](r,
db.Values{"email": profile.Email},
db.Values{"name": profile.Name},
)
if err != nil {
return web.Fail(err)
}
if created {
// Queue the welcome email to user.Email...
}Add a unique index on the lookup columns (such as slug or email) so concurrent requests cannot insert duplicate rows; when two requests race, the unique constraint catches the collision and the second call returns the row created by the first.
Upserts
To insert new rows and update existing ones in a single SQL statement (such as syncing a product feed), call model.Upsert with the models, the unique identifying columns, and the columns to update on conflict:
func ImportProducts(ctx context.Context) error {
products := []models.Product{
{SKU: "TSHIRT-M", Name: "T-shirt, medium", Price: 2500},
{SKU: "TSHIRT-L", Name: "T-shirt, large", Price: 2500},
}
_, err := model.Upsert(ctx, products, []string{"sku"}, "name", "price")
return err
}The identifying columns must have a unique index. On conflict, Upsert updates the listed columns alongside updated_at (or every non-identifying column except id and created_at when no update columns are passed). Like InsertMany, Upsert does not populate generated IDs or run hooks and events.
Replicating models
To copy an existing model into a new row (such as creating a billing address from a shipping address), call model.Replicate. It returns a copy with zeroed ID, timestamps, and relationships that you can modify and insert with model.Create:
billing := model.Replicate(shipping)
billing.Kind = "billing"
billing.Instructions = nil
if err := model.Create(r, &billing); err != nil {
return web.Fail(err)
}Any field you reset to its zero value (such as Instructions = nil) stores NULL or the column's database default when created.
Updating models
model.Update writes only the columns you specify along with updated_at, then reloads the updated fields onto the struct:
package posts
import (
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func Update(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
form, err := r.Validate[UpdatePost]()
if err != nil {
return web.Fail(err)
}
if err := model.Update(r, &post, db.Values{"title": form.Title}); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", &post)
}model.Update compares each value against the model's current field and skips the query, Updating hook, and Updated event when nothing changed. If the row no longer exists, Update returns *db.NotFoundError.
To update many rows in a single statement, check out Updating many rows.
Updating only the fields a request sends
For PATCH requests or partial forms where clients only send the fields they modified, wrap optional fields in validation.Sometimes and pass them directly inside db.Values. Laravel unwraps each present field and omits any field the request left out:
package profile
import (
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
"app/models"
)
type EditProfile struct {
Name validation.Sometimes[string] `json:"name"`
Bio validation.Sometimes[*string] `json:"bio"`
}
func (f *EditProfile) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Bio, rule.Max(1000)),
)
}
func Update(r *web.Request) *web.Response {
form, err := r.Validate[EditProfile]()
if err != nil {
return web.Fail(err)
}
user := r.User[models.User]()
if err := model.Update(r, user, db.Values{
"name": form.Name,
"bio": form.Bio,
}); err != nil {
return web.Fail(err)
}
return web.Back()
}With this form, {"name": "Taylor"} updates name without touching bio, while {"bio": null} clears bio without touching name. Passing Sometimes values directly in db.Values works across model.Update, model.Query[T]().Update, model.UpdateJoinRow, model.AttachWith, and model.SyncWith.
Saving every column
When you have already mutated several fields on a model struct, model.Save writes every column except id and created_at, refreshes updated_at, and reloads the stored row:
published := date.Now(r)
post.Title = "Release notes"
post.PublishedAt = &published
err := model.Save(r, &post)Save only updates existing rows and returns an error if the model has a zero ID; use model.Create for new records.
Incrementing a column
To atomically adjust a numeric counter (such as a post's vote count) without lost updates under concurrency, use model.Increment or model.Decrement. Both run in SQL (votes = votes + 1), refresh updated_at, run hooks and events, and update the struct with the stored value:
err := model.Increment(r, &post, "votes", 1)
err = model.Decrement(r, &post, "votes", 1)For other SQL expressions, pass db.Raw to model.Update, such as db.Values{"rating": db.Raw("rating * ?", 1.1)}.
Updating many rows
To update every row matching a query in a single UPDATE statement without loading models into memory, call Update on a model query. It refreshes updated_at automatically (unless you set it explicitly) and returns the number of affected rows:
package posts
import (
"go.laravel.com/date"
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
func PublishDrafts(r *web.Request) *web.Response {
user := r.User[models.User]()
_, err := model.Query[models.Post]().
WhereEq("user_id", user.ID).
WhereNull("published_at").
Update(r, db.Values{"published_at": date.Now(r)})
if err != nil {
return web.Fail(err)
}
return web.Back()
}Queries also support Increment and Decrement:
changed, err := model.Query[models.Post]().WhereNotNull("published_at").Increment(r, "votes", 1)Query updates validate column names against the model's schema and support JSON paths and db.Raw expressions. Because they modify rows directly in SQL without hydrating models, they do not run hooks or dispatch events. Query updates cannot include joins, OrderBy, or Limit.
Reloading from the database
To reload a model and any loaded relationships from the database in place, call model.Refresh:
if err := model.Refresh(r, &post); err != nil {
return web.Fail(err)
}To fetch a fresh copy from the database without mutating your existing struct (and without reloading relationships), call model.Fresh. Both return *db.NotFoundError if the row was deleted:
stored, err := model.Fresh(r, &post)Deleting models
To delete a model instance, pass it to model.Delete. If the row has already been deleted, Delete returns *db.NotFoundError:
func Destroy(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
if err := model.Delete(r, &post); err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.index")
}To delete several models by their primary keys while still running each model's Deleting hook and Deleted event, call model.Destroy. It loads and deletes the matching rows in one transaction, returning the count deleted and skipping missing IDs:
deleted, err := model.Destroy[models.Post](r, form.PostIDs...)To delete matching rows directly in SQL without loading models, call Delete on a model query. Like query updates, query deletes skip hooks and events:
deleted, err := model.Query[models.Post]().WhereNull("published_at").Delete(r)Models in transactions
Every function in the model package executes against the database connection carried by its context.Context. Inside db.Transaction, pass the callback's ctx to each model call so all writes commit or roll back together:
func Vote(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
err = db.Transaction(r, func(ctx context.Context) error {
vote := models.Vote{PostID: post.ID}
if err := model.Create(ctx, &vote); err != nil {
return err
}
return model.Increment(ctx, &post, "votes", 1)
})
if err != nil {
return web.Fail(err)
}
return web.JSON(post)
}Any call that passes r instead of ctx runs outside the transaction and will not roll back on error.
Serializing models
Models serialize directly to JSON when returned from web.JSON or passed as Inertia props using standard json struct tags.
To hide sensitive columns such as password hashes, remember tokens, or internal notes from JSON responses, tag them with json:"-". A crypt.Encrypted field without json:"-" fails to marshal so encrypted secrets cannot leak to the browser by accident:
// models/user.go
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"-"`
RememberToken *string `json:"-"`
InternalNotes *string `json:"-"`
CreatedAt time.Time `json:"created_at"`
}Standard json tag options work as usual, including omitzero (which omits unloaded relationships and zero values) and custom field names such as json:"createdAt".
When an endpoint needs a different JSON shape than your model, define a dedicated response struct and return it with web.JSON:
type PublicProfile struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
func Show(r *web.Request) *web.Response {
user, err := model.FromRoute[models.User](r, "user")
if err != nil {
return web.Fail(err)
}
return web.JSON(PublicProfile{ID: user.ID, Name: user.Name})
}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 are pointer-receiver methods that run inside each single-model write before the row changes, allowing you to mutate pending values or return an error to abort the write. Implement only the hooks you need:
// models/article.go
package models
import (
"context"
"errors"
"strings"
"time"
"go.laravel.com/db"
)
var ErrLocked = errors.New("the article is locked")
type Article struct {
ID int64 `json:"id"`
Title string `json:"title"`
Slug string `json:"slug"`
Locked bool `json:"locked"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (a *Article) Creating(ctx context.Context) error {
a.Slug = slug(a.Title)
return nil
}
func (a *Article) Updating(ctx context.Context, values db.Values) error {
if a.Locked {
return ErrLocked
}
if title, ok := values["title"].(string); ok {
values["slug"] = slug(title)
}
return nil
}
func (a *Article) Deleting(ctx context.Context) error {
if a.Locked {
return ErrLocked
}
return nil
}
func slug(title string) string {
return strings.ToLower(strings.Join(strings.Fields(title), "-"))
}| Hook | Receives | Runs |
|---|---|---|
Creating(ctx) | The model about to be inserted | Before an insert; the insert writes any changes the hook makes |
Updating(ctx, values) | The current model and the db.Values being written | Before an update; the update writes any changes made to values |
Deleting(ctx) | The model | Before a delete |
During Updating, the model still holds its previous values while values contains the incoming changes (or every column for model.Save), so read updated fields from values.
Hooks run inside the same transaction as the write, and ctx carries that transaction so any database queries made inside a hook roll back if the write fails. To map a hook error like ErrLocked to a specific HTTP status, either check errors.Is(err, models.ErrLocked) in your handler or give the error a StatusCode() int method.
Events
After each single-model write, Laravel dispatches a model.Created[M], model.Updated[M], or model.Deleted[M] event. 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:
// listeners/send_welcome_email.go
package listeners
import (
"context"
"go.laravel.com/model"
"app/models"
)
func SendWelcomeEmail(ctx context.Context, e model.Created[models.User]) error {
// Send the welcome email to e.Model.Email...
return nil
}Register the listener in listeners.All:
// listeners/listeners.go
var All = []laravel.Listener{
laravel.Listen(SendWelcomeEmail),
}Every model event exposes the affected record on e.Model. Inside a transaction, 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, register it with laravel.ListenAtDispatch.
model.Updated events also include e.Changes and e.Changed(column) to inspect which columns changed along with their Old and New values:
func NotifyPreviousEmail(ctx context.Context, e model.Updated[models.User]) error {
change, ok := e.Changed("email")
if !ok {
return nil
}
// Notify change.Old.(string) that the account now uses e.Model.Email...
return nil
}Muting events
To perform writes without dispatching model events (for example, inside a seeder that shouldn't send welcome emails), pass event.Muted(ctx). Model hooks still run, so derived fields such as slugs are still populated:
// database/seeders/users.go
package seeders
import (
"context"
"go.laravel.com/event"
"go.laravel.com/model"
"app/models"
)
func users(ctx context.Context) error {
users := []models.User{
{Name: "Taylor", Email: "taylor@laravel.com"},
{Name: "Abigail", Email: "abigail@laravel.com"},
}
return model.CreateMany(event.Muted(ctx), users)
}Which writes run hooks and events
Hooks and events run only for writes that operate on model instances. Bulk query writes, model.Upsert, and model.InsertMany modify rows directly in SQL without hydrating models, so they skip both:
| Write | Hook | Event |
|---|---|---|
model.Create, model.CreateMany, model.CreateRelated, and model.CreateManyRelated | Creating | Created |
model.FirstOrCreate | Creating on insert | Created on insert |
model.UpdateOrCreate | Creating on insert, Updating on update | Created on insert, Updated on update |
model.Update, model.Save, model.Increment, and model.Decrement | Updating | Updated |
model.Delete and model.Destroy | Deleting | Deleted for each model |
model.Upsert, model.InsertMany, and Update / Delete on a query | None | None |
Testing
In your tests, seed records with factories, exercise your routes, and verify database state with database assertions. Your application's tests.New helper refreshes the database automatically so every test starts with a clean schema:
// tests/feature/posts_test.go
func TestUsersCanDeleteTheirPosts(t *testing.T) {
client := tests.New(t)
user := client.Create(factories.User)
post := client.Create(factories.Post.For("user", user))
client.ActingAs(&user).Delete(fmt.Sprintf("/posts/%d", post.ID)).AssertRedirect("/posts")
client.AssertModelMissing(&post)
}Because auto-increment sequences continue incrementing across tests, assert against the IDs returned by your factories (such as post.ID) rather than hard-coded numbers like 1. To learn more about database assertions, refreshing and seeding test databases, and testing model events, check out the testing guide's section on database assertions.