Database
- Introduction
- Configuration
- Running queries
- Transactions
- Using more than one database
- Read and write connections
- Logging queries
- Listening for queries
- Using database/sql directly
- Testing
Introduction
Almost every modern web application interacts with a database. Built on Go's database/sql, Laravel provides first-party support for PostgreSQL, MySQL, MariaDB, and SQLite, whether you are writing raw SQL, using the fluent query builder, or working with models. All three find the database through the context you pass them, and join any transaction that context is in.
Most of your application's queries will go through models and the query builder. This guide walks through configuring your database connections, working with transactions and read replicas, and writing raw SQL when a query is clearest in SQL itself. To create and modify tables, see migrations.
Configuration
Laravel reads your database settings from your .env file. Set the database's connection string in DATABASE_URL. New applications point it at PostgreSQL:
DATABASE_URL=postgres://postgres@127.0.0.1/laravelLaravel selects the driver from the URL scheme: postgres://, mysql://, mariadb://, or sqlite:. Although MySQL and MariaDB share a driver, their SQL differs in places, so use mariadb:// for a MariaDB server so the query builder writes SQL that MariaDB accepts.
Drivers
Each database driver is a package of its own, so your program compiles only the drivers it uses. List them in the Drivers field of your application's options in bootstrap/app.go. New applications list the PostgreSQL driver:
// bootstrap/app.go
package bootstrap
import (
laravel "go.laravel.com"
"go.laravel.com/db"
"go.laravel.com/db/postgres"
)
func Options() laravel.Options {
return laravel.Options{
// ...
Drivers: []db.Driver{postgres.Driver},
}
}| Package | Driver | Databases |
|---|---|---|
db/postgres | postgres.Driver | PostgreSQL |
db/mysql | mysql.Driver | MySQL and MariaDB |
db/sqlite | sqlite.Driver | SQLite |
If DATABASE_URL uses a scheme that no driver in the list handles, your application stops when it starts, and the error names the driver to add.
SQLite
SQLite keeps the entire database in a single file with no separate server to run, making it convenient for local development and small applications. Its driver is written in Go, so it needs no C compiler. To use it instead of PostgreSQL, list sqlite.Driver in place of postgres.Driver in bootstrap/app.go, then point DATABASE_URL at the file:
DATABASE_URL=sqlite:storage/database.sqliteThe path is relative to your application's base path, and a URL such as sqlite:///var/data/app.sqlite holds an absolute path. Laravel creates the file on first use, provided its directory already exists, and turns on foreign key constraints so SQLite enforces them as the other databases do.
Defining more connections
When your application talks to more than one database, such as a separate reporting database, add named connections to cfg.Database.Connections in your options' configure function, which Laravel runs for your application and its tests. Read each connection's URL from a variable of your choosing:
// bootstrap/app.go
package bootstrap
import "go.laravel.com/config"
func configure(cfg *config.Config, env *config.Env) {
cfg.Database.Connections = map[string]config.Connection{
"reporting": {
URL: env.String("REPORTING_DATABASE_URL", ""),
MaxConnections: 20,
},
}
}A named connection uses the drivers in Options.Drivers, so list the driver for each URL's scheme. If a connection's URL is empty, such as when the variable isn't set on your machine, each query on the connection fails with an error that says so.
Once your application defines named connections, DB_CONNECTION may make one of them the default database in place of DATABASE_URL, such as to switch between a local SQLite file and PostgreSQL:
DB_CONNECTION=sqliteBy default, each connection keeps a pool of up to 10 open connections. Under heavy concurrency, you may raise the default connection's pool size with DB_MAX_CONNECTIONS, keeping the combined total across every copy of your application below your database server's connection limit:
DB_MAX_CONNECTIONS=25For named connections, set the MaxConnections field of config.Connection, as reporting does above. Laravel opens connections lazily on the first query, so an unreachable database does not prevent your application from starting.
If every new pooled connection needs session settings, such as a PostgreSQL search_path or a SQLite PRAGMA, list those statements in Init on cfg.Database.Init or a named config.Connection:
func configure(cfg *config.Config, env *config.Env) {
cfg.Database.Init = []string{"set search_path to app, public"}
}To run a query on a named connection, see Using more than one database.
说明
Tests ignore DB_CONNECTION, because RefreshDatabase names its test database after DATABASE_URL. To run your tests on another database, set DATABASE_URL for that run, such as DATABASE_URL=mysql://root@127.0.0.1/laravel go test ./....
Time precision
By default, each database connection stores times with microsecond precision (6 fractional digits of seconds), matching the maximum precision supported by PostgreSQL and MySQL. Before a query writes a time.Time, Laravel truncates it to the connection's precision rather than letting the database round it, and the schema builder's time columns use the same precision by default. That way, a row written at date.Now(ctx) is never rounded forward into the future, so a query for records up to now always finds it.
To store whole seconds instead, or any precision from 0 to 6 digits, set DB_TIME_PRECISION in your .env file:
DB_TIME_PRECISION=0For named connections, set the TimePrecision field of config.Connection in your configure function, from time.Microsecond to time.Second:
cfg.Database.Connections = map[string]config.Connection{
"legacy": {
URL: env.String("LEGACY_DATABASE_URL", ""),
TimePrecision: time.Second,
},
}When customizing a column with .Precision(n) in a migration, give it at least the connection's precision. A column with less precision than its connection causes the database to round incoming values instead of truncating them, while a column with higher precision still only receives values truncated to the connection's precision.
说明
If you change DB_TIME_PRECISION in an application that has already run migrations, write a new migration to update your existing time columns with .Precision(n).Change().
Driver options
Your database host may require TLS, or you may want a shorter connection timeout than the default. Put settings like these in the URL's query string, using the parameter names your driver reads:
# PostgreSQL
DATABASE_URL=postgres://app:secret@db.internal/app?sslmode=require
# MySQL and MariaDB
DATABASE_URL=mysql://app:secret@db.internal/app?tls=truePostgreSQL takes the same parameters as its psql tool, such as sslmode and connect_timeout. MySQL and MariaDB take the options of Go's MySQL driver, such as tls and timeout. If your password contains characters such as @, /, or :, percent-encode it in the URL, so p@ss becomes p%40ss.
Running queries
Once your connection is configured, you may run queries with db.Select, db.SelectOne, and db.Exec. Write your SQL as usual, and put a ? wherever a value goes. Laravel binds each value as a query parameter, so a value can never inject SQL. This handler finds a user by the ID in the URL, and responds with a 404 when there's no such user:
// handlers/users/users.go
package users
import (
"go.laravel.com/db"
"go.laravel.com/web"
)
func Show(r *web.Request) *web.Response {
id, err := r.PathInt("user")
if err != nil {
return web.Fail(err)
}
type userSummary struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
user, err := db.SelectOne[userSummary](r, "select id, name from users where id = ?", id)
if err != nil {
return web.Fail(err)
}
return web.JSON(user)
}? works on every database. On PostgreSQL, Laravel numbers the placeholders $1, $2, and so on before it sends the query, so that's what you'll see in its errors and your log.
The first argument is a context.Context that carries your application, and db finds your database through it. In a handler, pass the request, so the query also stops when the request ends. Code below your handlers takes a context.Context instead, and runs its queries with it:
// orders/orders.go
package orders
import (
"context"
"go.laravel.com/db"
)
func Ship(ctx context.Context, id int64) error {
_, err := db.Exec(ctx, "update orders set status = 'shipped' where id = ?", id)
return err
}A handler calls orders.Ship(r, id). Console commands, queued jobs, listeners, and tests also receive a context that carries your application, so they may call orders.Ship too. When the caller is inside a transaction, the function's queries join that transaction.
Running a select query
To read rows, give db.Select the row type in brackets, and it returns a slice of every row. db.SelectOne returns only the first row. Each row scans into a struct by column name, as Mapping rows to structs describes:
// users/users.go
package users
import (
"context"
"go.laravel.com/db"
"app/models"
)
func Verified(ctx context.Context) ([]models.User, error) {
return db.Select[models.User](ctx, "select * from users where email_verified_at is not null")
}When a query selects a single column, such as each user's email address or a count, each row scans into a plain value instead:
emails, err := db.Select[string](ctx, "select email from users where name like ?", "T%")
count, err := db.SelectOne[int64](ctx, "select count(*) from users")When no row matches, Select returns an empty slice, and SelectOne returns a *db.NotFoundError, which responds with a 404, as Handling errors describes. (When you need to scan into an existing pointer, such as in reflection helpers, db.SelectInto and db.SelectOneInto take a pointer destination.)
When calling a stored procedure on MySQL or MariaDB that returns multiple result sets, such as a customer's details and then their orders, use db.SelectSets. It scans each result set into the slice at the same position in its list:
var users []models.User
var orders []models.Order
err := db.SelectSets(ctx, []any{&users, &orders}, "call customer_summary(?)", 42)Running insert, update, and delete statements
Use Exec to run statements that change rows. It returns a sql.Result, whose RowsAffected method returns the number of rows the statement changed:
_, err := db.Exec(ctx, "insert into users (name, email) values (?, ?)", "Taylor", "taylor@example.com")
if err != nil {
return err
}
result, err := db.Exec(ctx, "update users set votes = 100 where name = ?", "Taylor")
if err != nil {
return err
}
updated, err := result.RowsAffected()Run statements that return nothing, such as drop table, with Exec too. To get the new row's ID back, see Returning inserted IDs.
To run multiple statements separated by semicolons without preparing them or binding values, use db.Unprepared:
_, err := db.Unprepared(ctx, `
create table audit_logs (id integer primary key, message text);
create index audit_logs_message_index on audit_logs (message);
`)警告
Never interpolate user input into db.Unprepared. It sends the SQL directly without parameter binding.
Binding values
Each ? binds one value, in the order you pass them. A value may be a string, a number, a bool, a time.Time, a []byte, or a pointer to one of those, and a nil pointer binds NULL:
var nickname *string // nil, so the column becomes NULL
_, err := db.Exec(ctx, "update users set nickname = ? where id = ?", nickname, 42)To match against a list, such as the users who have any of several roles, wrap the slice in db.In. It binds one value per item in place of its ?:
roles := []string{"admin", "editor"}
users, err := db.Select[models.User](ctx, "select * from users where role in (?)", db.In(roles))An empty slice returns an error without running the query, because in () isn't valid SQL, so check for one first when the list comes from input. A slice passed without db.In binds as a single value, which most drivers refuse.
Inserting many rows
To insert a slice in one statement, such as a list of users you're importing, pass it with db.Rows after values. db.Rows writes one parenthesized row per item, holding the columns you name in that order. Each item is either a struct, whose fields map to columns as Mapping rows to structs describes, or a db.Values:
type NewUser struct {
Name string
Email string
}
users := []NewUser{
{Name: "Taylor", Email: "taylor@example.com"},
{Name: "Jess", Email: "jess@example.com"},
}
result, err := db.Exec(ctx, "insert into users (name, email) values ?", db.Rows(users, "name", "email"))Put db.Rows's ? directly after values, without parentheses around it. Each column of each row is a parameter, and PostgreSQL and MySQL allow 65,535 parameters in one query, while SQLite allows 32,766. Insert a larger slice in chunks.
Mapping rows to structs
Most queries read rows into your own structs. Laravel matches each field to the column with the field's name in snake case, so CreatedAt reads created_at and UserID reads user_id. A db tag names another column, and db:"-" skips the field. Give a column that may be NULL a pointer field, which is nil for NULL:
type Subscriber struct {
ID int64 `json:"id"`
Email string `json:"email" db:"email_address"`
Nickname *string `json:"nickname"`
GitHubLogin string `json:"github_login" db:"github_login"`
ConfirmedAt *time.Time `json:"confirmed_at"`
Unread int `json:"unread" db:"-"`
}
subscribers, err := db.Select[Subscriber](ctx, "select * from subscribers order by id")Watch for names that Go capitalizes inside a word: GitHubLogin reads git_hub_login unless a tag says github_login. The db and json tags are separate, so a struct that you return as JSON needs both.
Mapping ignores extra columns. A NULL in a field that isn't a pointer returns an error. When a model or a query builder query reads every column, a field without a column is an error too, so a misspelled tag fails with db: subscribers has no column git_hub_login for Subscriber.GitHubLogin. Tag a field that isn't a column with db:"-", as the example does for Unread.
When several tables share columns, such as created_at and updated_at, you may put those fields in a struct of their own and embed it. The embedded struct's fields map to columns as if the outer struct declared them:
type Timestamps struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type Post struct {
ID int64 `json:"id"`
Title string `json:"title"`
Timestamps
}Returning inserted IDs
After an insert, you'll often need the new row's ID, such as to redirect to the page that shows it. The query builder's InsertGetID returns it on every database. In raw SQL on PostgreSQL, SQLite, and MariaDB, write a returning clause and read the ID with SelectOne:
id, err := db.SelectOne[int64](ctx, "insert into users (name) values (?) returning id", "Taylor")MySQL does not support returning. Run the insert with Exec, and read the auto-increment ID with the sql.Result's LastInsertId method, which works on MySQL, MariaDB, and SQLite:
result, err := db.Exec(ctx, "insert into users (name) values (?)", "Taylor")
if err != nil {
return err
}
id, err := result.LastInsertId()To get whole rows back from an insert, update, or delete, including the defaults and keys the database filled in, use the query builder's InsertReturning, UpdateReturning, or DeleteReturning methods (supported on PostgreSQL, SQLite, and, for inserts and deletes, MariaDB).
JSON columns and types of your own
Some data has a shape but no columns of its own, such as a user's notification preferences. Store it in a json column, and declare its field as a db.JSON of the Go type it holds:
import "go.laravel.com/db"
type Preferences struct {
Theme string `json:"theme"`
Notifications bool `json:"notifications"`
}
type User struct {
ID int64 `json:"id"`
Roles db.JSON[[]string] `json:"roles"`
Preferences *db.JSON[Preferences] `json:"preferences"`
}A db.JSON holds its value in the field V, as the standard library's sql.Null does. Wrap values with db.NewJSON, bind them in queries as you would a string or a number, and read V once the row is scanned:
preferences := db.NewJSON(Preferences{Theme: "dark", Notifications: true})
_, err := db.Exec(ctx, "update users set preferences = ? where id = ?", preferences, 42)
user, err := db.SelectOne[User](ctx, "select id, roles, preferences from users where id = ?", 42)
theme := user.Preferences.V.ThemeDeclare a nullable column's field as a pointer, such as *db.JSON[Preferences], which is nil for NULL. When you return the user as JSON, a db.JSON field encodes as the value it holds, such as "roles": ["admin", "billing"], rather than as an object with a V key. To filter by a key inside the document, such as every user whose theme is dark, check out the query builder's section on JSON columns.
For custom conversions, such as a brand color stored as text like #ff2d20, give your type a Value method, which returns what to write, and a Scan method, which reads the column back. These are the standard library's driver.Valuer and sql.Scanner interfaces:
import (
"database/sql/driver"
"fmt"
)
type Color struct {
R, G, B uint8
}
func (c Color) Value() (driver.Value, error) {
return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B), nil
}
func (c *Color) Scan(src any) error {
var text string
switch src := src.(type) {
case string:
text = src
case []byte:
text = string(src)
default:
return fmt.Errorf("color: can't scan a %T", src)
}
_, err := fmt.Sscanf(text, "#%02x%02x%02x", &c.R, &c.G, &c.B)
return err
}Scan accepts both a string and bytes, because some drivers return a text column as a string and others as bytes.
Enums, UUIDs, and IP addresses
To store one of a few fixed values, such as a post's status, declare a string type with a constant for each value. A string type binds and scans as the string it holds, so it needs no methods of its own:
type Status string
const (
Draft Status = "draft"
Published Status = "published"
)
_, err := db.Exec(ctx, "update posts set status = ? where id = ?", Published, 42)For UUIDs, use the standard library's uuid.UUID, and for IP addresses, netip.Addr. Laravel writes each one as text, such as 203.0.113.7, and reads the text back into the type, on every database. The schema builder's UUID and IPAddress columns hold that text:
import (
"context"
"net/netip"
"uuid"
"go.laravel.com/db"
)
func RecordLogin(ctx context.Context, userID int64, ip netip.Addr) error {
_, err := db.Exec(ctx,
"insert into logins (id, user_id, ip_address) values (?, ?, ?)",
uuid.NewV7(), userID, ip,
)
return err
}Any type of your own with both a MarshalText and an UnmarshalText method writes and reads as text too, unless it's a string, a number, or a bool, or it has Value and Scan methods. Reading a value that UnmarshalText refuses returns an error. A nullable column needs a pointer field, such as *netip.Addr.
Dates, times, and decimals
Store moments, such as when an order was paid, as time.Time, and calendar dates with no time of day, such as the day an order ships, as date.Date. A nullable column needs a pointer field, such as *time.Time:
import (
"context"
"time"
"go.laravel.com/date"
"go.laravel.com/db"
)
type Order struct {
ID int64 `json:"id"`
ShipsOn date.Date `json:"ships_on"`
PaidAt *time.Time `json:"paid_at"`
}
func MarkPaid(ctx context.Context, id int64) (Order, error) {
_, err := db.Exec(ctx, "update orders set paid_at = ? where id = ?", date.Now(ctx), id)
if err != nil {
return Order{}, err
}
return db.SelectOne[Order](ctx, "select id, ships_on, paid_at from orders where id = ?", id)
}| Go type | What it holds | PostgreSQL | MySQL | SQLite |
|---|---|---|---|---|
date.Date | A calendar date | date | DATE | Text |
time.Time | A moment | timestamptz or timestamp | TIMESTAMP or DATETIME | Text |
Laravel writes every time.Time in UTC, whatever its location, and reads times back in UTC, so a time.Time field reads the schema builder's Timestamps() columns on every database, even though some of those columns have no timezone.
For exact decimals such as prices or account balances, use numeric.Decimal rather than a float64, because floats round: 0.1 + 0.2 is 0.30000000000000004. For example, this function adds a shipping charge to an order's total:
import (
"context"
"go.laravel.com/db"
"go.laravel.com/numeric"
)
func AddShipping(ctx context.Context, id int64) error {
total, err := db.SelectOne[numeric.Decimal](ctx, "select total from orders where id = ?", id)
if err != nil {
return err
}
total = total.Add(numeric.MustParse("4.99"))
_, err = db.Exec(ctx, "update orders set total = ? where id = ?", total, id)
return err
}Add, Sub, and Mul are exact, while Div and Round round half away from zero to the number of places you give them. Compare decimals with Cmp or Equal rather than ==, because == can report two equal amounts, such as 1.5 and 1.50, as different. Give a nullable column a *numeric.Decimal field. A Decimal encodes to JSON as a string, such as "149.99", so a JavaScript client keeps every digit.
Decimal maps to a decimal column, which the schema builder creates with table.Decimal. Parse decimals from text with numeric.Parse rather than from floats, so they preserve every digit. Because SQLite has no exact decimal type and stores a decimal column's fractions as floats, which hold about 15 digits, store higher-precision decimals in a text column on SQLite.
Streaming results
Select loads every matching row into memory at once, which can exhaust memory when processing large tables such as a full subscriber list. To process rows one at a time, range over db.Cursor, which scans each row into the type you name as the database sends it:
for subscriber, err := range db.Cursor[Subscriber](ctx, "select * from subscribers order by id") {
if err != nil {
return err
}
// Send the newsletter...
}The cursor keeps a connection from the pool until the loop ends, so keep slow work out of the loop. To update the rows as you go, use the query builder's LazyByID, which reads a page of rows at a time.
Handling errors
A query that fails returns a *db.QueryError, so passing it to web.Fail from a handler produces a 500 response and reports the error. The error's message includes the database error and the SQL, but leaves out the bound values, so passwords and tokens stay out of your log.
Two kinds of failure usually need a different answer than a 500:
- When
SelectOnefinds no row, it returns a*db.NotFoundError, which responds with a404, so a handler that shows a record needs no check of its own. To handle a missing row yourself, checkdb.IsNotFound(err), which matches both*db.NotFoundErrorandsql.ErrNoRows. - When a write breaks a unique index, such as a second account with the same email address,
db.IsUniqueViolation(err)reports it.
For example, this handler subscribes an email address to a newsletter. When the address is already subscribed, it shows the user a validation error instead of a 500:
// handlers/subscribers/subscribers.go
package subscribers
import (
"go.laravel.com/db"
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
"go.laravel.com/web"
)
type Subscribe struct {
Email string `json:"email"`
}
func (f *Subscribe) Rules() validation.Rules {
return validation.For(f, rule.Field(&f.Email, rule.Required, rule.Email))
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[Subscribe]()
if err != nil {
return web.Fail(err)
}
_, err = db.Exec(r, "insert into subscribers (email_address) values (?)", form.Email)
if db.IsUniqueViolation(err) {
return web.Invalid("email", "That email address is already subscribed.")
}
if err != nil {
return web.Fail(err)
}
return web.Back().With("status", "You're subscribed!")
}To classify other common database errors across PostgreSQL, MySQL, MariaDB, and SQLite, db.FailureOf(err) returns the kind of failure:
| Failure | Matches |
|---|---|
db.UniqueViolation | Unique or primary key constraint violation |
db.ForeignKeyViolation | Foreign key constraint violation |
db.CheckViolation | Check constraint violation |
db.Deadlock, db.LockTimeout | A transaction the database cancelled, or a statement that gave up waiting for a lock |
db.ConnectionFailure, db.MissingDatabase | A connection that couldn't open, or a database that doesn't exist |
db.LostConnection | Dropped connection, server restart, or failed-over primary that now refuses writes |
db.InvalidValue | A value that a column's type can't hold |
Transactions
When transferring funds between two accounts, both updates must succeed or fail together. Use db.Transaction to run a function inside a database transaction. Laravel commits when the function returns nil, and rolls back when it returns an error or panics. The function receives a context that's in the transaction, and every query you run with it joins the transaction:
// accounts/accounts.go
package accounts
import (
"context"
"go.laravel.com/db"
)
func Transfer(ctx context.Context, from, to, amount int64) error {
return db.Transaction(ctx, func(ctx context.Context) error {
_, err := db.Exec(ctx, "update accounts set balance = balance - ? where id = ?", amount, from)
if err != nil {
return err
}
_, err = db.Exec(ctx, "update accounts set balance = balance + ? where id = ?", amount, to)
return err
})
}Transaction returns the function's error as it is, so a *db.NotFoundError inside still responds with a 404, and errors.Is still matches your own errors. When the transaction produces a value, use db.TransactionValue (or db.TransactionValueWithAttempts) so you don't need to declare a variable outside the closure:
order, err := db.TransactionValue(r, func(ctx context.Context) (models.Order, error) {
return createOrder(ctx, form)
})To run a transaction on a named connection, pass Transaction or TransactionValue the context that db.Connection returns.
Inside the function, everything that runs with its context joins the transaction: raw queries, the query builder, model writes and their hooks, factories, the Unique and Exists validation rules, and any function of yours that you pass the context to. Writes to the database cache store join it too, when the cache lives on the same database.
Calling db.Transaction with a context that's already in a transaction creates a savepoint. When the inner function fails, only its writes roll back, and the outer transaction carries on. So a function such as accounts.Transfer may wrap its own writes in db.Transaction, and it works the same whether or not its caller is in a transaction.
A few queries behave differently inside a transaction:
- A goroutine that you start yourself and that queries after
Transactionreturns fails withdb.ErrTransactionEnded, because the transaction is gone. Wait for the work inside the function, or give the goroutinedb.Outside(ctx). - To write something that must survive a rollback, such as a record of a failed payment attempt, run it with
db.Outside(ctx), which returns a copy of the context whose queries run outside the transaction. On SQLite, which lets one transaction write at a time, make such writes before the transaction begins or after it ends, because they wait for the transaction's lock. - A query inside a
db.Cursorloop fails withdb.ErrCursorOpen, because the cursor holds the transaction's connection. Read the rows withSelectfirst. - MySQL and MariaDB commit the transaction when they run a statement that changes a table, such as
create table, so keep schema changes out of transactions.
Handling deadlocks
Under high concurrency, two transactions can deadlock, and the database cancels one of them. TransactionWithAttempts runs the function again when a deadlock or lock wait timeout occurs, up to the total number of attempts you give it:
err := db.TransactionWithAttempts(ctx, 3, func(ctx context.Context) error {
_, err := db.Exec(ctx, "update accounts set balance = balance + 1 where id = ?", 42)
return err
})Other errors, such as a unique violation, don't retry. Keep side effects that can't run twice, such as sending an email, out of the function, and hold them until the commit with AfterCommit instead.
Work after the commit
Some work should happen only once the data it describes is committed, such as emailing a receipt for an order. db.AfterCommit registers that work from anywhere inside a transaction, without passing the transaction around. This function records an order, and sends the receipt once the order is committed:
import (
"context"
"go.laravel.com/db"
"app/store"
)
func PlaceOrder(ctx context.Context, email string, total int64) error {
_, err := db.Exec(ctx, "insert into orders (email, total) values (?, ?)", email, total)
if err != nil {
return err
}
return db.AfterCommit(ctx, func(ctx context.Context) error {
return store.SendReceipt(ctx, email, total)
})
}
err := db.Transaction(ctx, func(ctx context.Context) error {
return PlaceOrder(ctx, "taylor@example.com", 4999)
})Here app/store stands for a package of your own. When no transaction is active, the function runs immediately. If the transaction rolls back, Laravel discards it. Inside a savepoint, the function waits until the outermost transaction commits.
If a held function fails, the data is already committed, so there's nothing for the caller to undo. Transaction reports the error as a *db.AfterCommitError and returns nil, and the held functions after the failed one don't run.
Held functions live in memory, so they are lost if the process stops before they run. For durable follow-up work, dispatch a queued job instead. Jobs and events dispatched with a context that's in a transaction wait for the commit automatically.
Managing a transaction yourself
db.Transaction commits and rolls back for you, and it's the right choice for most code. When you need to decide yourself when to commit or roll back, call Begin on the *db.DB that db.From returns, then Commit or Rollback on the transaction that Begin returns. Rolling back a committed transaction does nothing, so defer Rollback right after Begin, and any early return rolls the transaction back:
tx, err := db.From(ctx).Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, "insert into notes (body) values ('Keep this note')"); err != nil {
return err
}
savepoint, err := tx.Begin(ctx)
if err != nil {
return err
}
if _, err := savepoint.Exec(ctx, "insert into notes (body) values ('Discard this note')"); err != nil {
return err
}
if err := savepoint.Rollback(ctx); err != nil {
return err
}
return tx.Commit(ctx)Calling Begin on a transaction creates a savepoint, as the example shows. The query builder and models join the transaction only when you give them tx.Context(ctx), which returns a copy of the context whose queries run on tx.
Concurrent work in a transaction
Sometimes the work inside a transaction splits into parts that don't depend on each other, such as reserving the stock of each item in an order while calling a warehouse service. A transaction runs on one connection, which runs one query at a time, so the parts' queries take turns, while their other work runs at the same time. A nested db.Transaction keeps the connection until it ends, so another part's writes can't land inside its savepoint. To run parts in goroutines of your own, give each goroutine db.Concurrent(ctx), which marks its queries as work that waits for the others:
// orders/orders.go
package orders
import (
"context"
"errors"
"sync"
"go.laravel.com/db"
"app/inventory"
"app/models"
)
func Reserve(ctx context.Context, items []models.OrderItem) error {
return db.Transaction(ctx, func(ctx context.Context) error {
var wg sync.WaitGroup
errs := make([]error, len(items))
for i, item := range items {
wg.Go(func() {
errs[i] = inventory.Reserve(db.Concurrent(ctx), item)
})
}
wg.Wait()
return errors.Join(errs...)
})
}Here app/inventory stands for a package of your own whose Reserve runs its own queries and nested transactions. The task package's functions, such as task.Run, give each function a db.Concurrent context for you.
A goroutine without db.Concurrent fails with db.ErrSavepointOpen while another goroutine's nested transaction is open. Inside a nested db.Transaction, run queries with the ctx that the inner function receives, because a query with the outer function's ctx fails with the same error.
Using more than one database
db.Select, db.Exec, and the rest run on your default database. To run queries on a named connection, pass a context and the connection's name to db.Connection. It returns a copy of the context whose queries run on that connection, so raw SQL, the query builder, models, and transactions all run there when you give them that context:
func Totals(r *web.Request) *web.Response {
type regionTotal struct {
Region string `json:"region"`
Total int64 `json:"total"`
}
reporting := db.Connection(r, "reporting")
totals, err := db.Select[regionTotal](
reporting,
"select region, sum(total) as total from sales group by region",
)
if err != nil {
return web.Fail(err)
}
return web.JSON(totals)
}A name that isn't in cfg.Database.Connections panics with the names that are, because a misspelled name is a mistake in your code rather than in the request. To run your migrations on a named connection, pass its name to migrate --database.
Because Laravel does not translate raw SQL across database engines, you may check the connection's Dialect when writing database-specific SQL. For example, PostgreSQL's like is case-sensitive, so a search for names uses ilike there:
query := "select * from users where name like ?"
if db.From(ctx).Dialect() == db.Postgres {
query = "select * from users where name ilike ?"
}
users, err := db.Select[models.User](ctx, query, "tay%")The dialects are db.Postgres, db.MySQL, db.MariaDB, and db.SQLite.
Opening databases at runtime
Some applications keep each customer in a database of its own, and store each customer's database URL in a table rather than in configuration. Open such a database with db.Open, which takes the URL and the drivers to choose from. A *db.DB's Context method returns a copy of a context whose queries run on it:
conn, err := db.Open(db.Config{URL: customer.DatabaseURL, MaxConnections: 5}, postgres.Driver)
if err != nil {
return err
}
ctx = conn.Context(ctx)
unpaid, err := db.Table("invoices").WhereEq("paid", false).Count(ctx)A *db.DB is a pool of connections, and db.Open doesn't connect until the first query. Open each customer's database once, such as in a map that one of your services keeps behind a mutex, and reuse it, because opening one for each request would leave its connections open. Call Close on a *db.DB you no longer need to close its pool.
Read and write connections
As your traffic grows, you may want to send select statements to read replicas and every write to your primary database. List the replicas' hosts in DB_READ_HOSTS:
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,replica-2.internal:5433
DB_STICKY=trueEach replica connects with DATABASE_URL's credentials, database, and options, and changes only the host. A host without a port, such as replica-1.internal, uses DATABASE_URL's port. Laravel picks a replica at random for each select.
Sometimes a replica needs its own credentials, such as a read-only user, or a different database name. For that replica, list its full URL instead of its host, and Laravel uses the URL as written. You may mix both forms in one list:
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,postgres://reader:secret@replica-2.internal/appIf your provider gives the primary its own URL, such as a writer endpoint that fails over to a new primary, set it in DB_WRITE_URL. Writes and transactions then use DB_WRITE_URL, while host-only replicas still take their credentials, database, and options from DATABASE_URL:
DATABASE_URL=postgres://app:secret@db.internal/app
DB_WRITE_URL=postgres://app:secret@writer.db.internal/app
DB_READ_HOSTS=reader-1.db.internal,reader-2.db.internalEvery URL on a connection must use the same database driver, so you can't pair a PostgreSQL writer with MySQL replicas. For a named connection, set the WriteURL, ReadHosts, and Sticky fields of its config.Connection instead.
A select outside a transaction reads from a replica, unless it locks rows with LockForUpdate or SharedLock. Every other statement, and every query in a transaction, uses the primary: DB_WRITE_URL when it's set, and DATABASE_URL otherwise. Raw queries, the query builder, and models all follow these rules.
Replicas can lag briefly behind the primary. With DB_STICKY set to true, once a request, queued job, or console command writes to a connection, its later reads on that connection use the primary, so it always reads its own writes. To force a single query onto the primary, such as one that reads a row another request wrote a moment ago, run the query on db.Writer(r):
post, err := db.Table("posts").On(db.Writer(r)).Find[models.Post](r, id)To send every read to the primary for the rest of the request, call db.ReadFromWriter with the request:
db.ReadFromWriter(r)Preventing stale reads across requests
When someone edits a post and the browser loads it again, a replica may still have the old title. To give replicas time to catch up, append PreventStaleDatabaseReads to the web middleware group in bootstrap/app.go:
import (
laravel "go.laravel.com"
"go.laravel.com/config"
"go.laravel.com/middleware"
)
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Web.Append(middleware.PreventStaleDatabaseReads{})
},For two seconds after a request writes to the default database connection and finishes, later requests in the same session read from that connection's primary. Reads on other connections and requests from other sessions keep their usual routing. Keep DB_STICKY=true if reads in the request that made the write should also use the primary.
If replicas typically take longer to catch up, set a longer window with middleware.PreventStaleDatabaseReads{Window: 5 * time.Second}. The middleware must run after the session starts, on both the route that writes and the route that reads.
Logging queries
To see each query your application runs while you develop, set LOG_LEVEL to debug:
LOG_LEVEL=debugLaravel then logs each query with its SQL and how long it took, leaving out the bound values. A query that a handler runs carries the request's ID, so you can find every query that one request made:
time=2026-11-10T14:03:27.512Z level=DEBUG msg=query sql="select * from users where id = $1" duration_ms=0.42 dialect=postgres request_id=6f1c0a9d2b3e4f5a8c7d9e0f1a2b3c4dListening for queries
To act on each query your application runs, such as to report slow ones, give your options a QueryListener in bootstrap/app.go:
// bootstrap/app.go
package bootstrap
import (
"context"
"log/slog"
"time"
laravel "go.laravel.com"
"go.laravel.com/db"
)
func Options() laravel.Options {
return laravel.Options{
// ...
QueryListener: func(ctx context.Context, q db.ExecutedQuery) {
if q.Duration > 500*time.Millisecond {
slog.WarnContext(
ctx,
"slow query",
"connection", q.Connection,
"sql", q.SQL,
"duration", q.Duration,
)
}
},
}
}Laravel calls the listener after every successful query across all connections, including the begins, commits, rollbacks, and savepoints of transactions. It receives the context that ran the query and a db.ExecutedQuery, exposing SQL, Duration, Dialect, and Connection, such as default or reporting. The SQL keeps its placeholders but not the bound values, so passwords and tokens stay out of your logs. The listener runs before the query returns (or once the rows close for queries that return rows), so keep it fast. For a connection you open yourself with db.Open, set the Listener field of its db.Config.
Using database/sql directly
When you need something Laravel doesn't wrap, use database/sql's own methods. A *db.DB has ExecContext, QueryContext, QueryRowContext, and PrepareContext, so you may pass it to a library that calls those methods, such as the code that sqlc generates. db.From returns the context's *db.DB. Inside db.Transaction, that *db.DB is the transaction, so the library's queries join the transaction:
// sqlc generated the queries package from your SQL.
post, err := queries.New(db.From(r)).FindPost(r, id)These methods send the SQL to the driver as written, so a query uses the driver's own placeholders: $1, $2, and so on on PostgreSQL, and ? on MySQL and SQLite. A missing row is sql.ErrNoRows rather than a *db.NotFoundError, so check for it with errors.Is and return web.Abort(http.StatusNotFound) when that's what you want.
If a library needs a *sql.DB, the Pool method returns the underlying one. Queries on that *sql.DB skip Laravel's query listeners and never join a transaction, even when you call Pool on a transaction.
Testing
Tests that touch the database need tables to query and a clean slate each time. New applications pass laraveltest.RefreshDatabase in tests/tests.go, so each test gets a database beside yours, such as laravel_test_1, built by your migrations, and runs in a transaction that rolls back when the test ends. The test's requests and the code you call with client.Context() run in that transaction. For a complete overview of database assertions, seeding, and refreshing the database in tests, check out the testing guide's section on testing the database.