Skip to content

Getting Started

Database

Database

Introduction

Almost every modern web application interacts with a database. Built on SQLx, Laravel provides first-party support for PostgreSQL, MySQL, MariaDB, and SQLite, whether you are working with raw SQL via db::query!, the fluent query builder, or models.

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

Database settings live in src/config/database.rs. New applications define a single postgres connection by default. Configure the default connection name with DB_CONNECTION and its connection string with DATABASE_URL:

1DB_CONNECTION=postgres
2DATABASE_URL=postgres://[email protected]/laravel
1DB_CONNECTION=postgres
2DATABASE_URL=postgres://[email protected]/laravel

Laravel selects the driver from the URL scheme: postgres://, mysql://, mariadb://, or sqlite:. Although MySQL and MariaDB share a wire protocol, their SQL syntax differs in places, so use mariadb:// for MariaDB servers so the query builder generates MariaDB-compatible SQL.

Drivers

Each database driver is enabled via a Cargo feature on laravel-rust so your application only compiles the drivers it uses. New applications enable database-postgres in Cargo.toml. To switch drivers or add another database engine, update the feature list in Cargo.toml:

1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "database-sqlite"] }
1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "database-sqlite"] }
Feature Databases
database-postgres PostgreSQL
database-mysql MySQL and MariaDB
database-sqlite SQLite

Without a driver feature, the laravel::db module doesn't exist, and the database session, cache, and queue drivers can't run.

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. To use it instead of PostgreSQL, replace database-postgres with database-sqlite in Cargo.toml, then configure your .env file:

1DB_CONNECTION=sqlite
2DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc
1DB_CONNECTION=sqlite
2DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc

The path is relative to your application's root directory. mode=rwc creates the file on first use, provided the parent directory already exists.

You may also set SQLite's journal_mode, synchronous, and busy_timeout (in milliseconds) in the URL. Options you leave out keep their defaults. For example, the wal journal mode lets reads continue while another connection writes:

1DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc&journal_mode=wal&synchronous=normal
1DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc&journal_mode=wal&synchronous=normal

Defining more connections

When your application talks to more than one database, such as a separate reporting database, register additional named connections in src/config/database.rs. Start from Database::from_env(env) so your default connection continues to read DB_CONNECTION, DATABASE_URL, DB_MAX_CONNECTIONS, DB_TIME_PRECISION, and the read and write variables from the environment:

1use laravel::config::database::{ConnectionConfig, Database};
2use laravel::config::{self, Env};
3 
4#[config::section]
5fn database(env: &Env) -> Database {
6 let mut database = Database::from_env(env);
7 
8 database.add_connection(
9 "reporting",
10 ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default())
11 .max_connections(20),
12 );
13 
14 database
15}
1use laravel::config::database::{ConnectionConfig, Database};
2use laravel::config::{self, Env};
3 
4#[config::section]
5fn database(env: &Env) -> Database {
6 let mut database = Database::from_env(env);
7 
8 database.add_connection(
9 "reporting",
10 ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default())
11 .max_connections(20),
12 );
13 
14 database
15}

By default, each connection maintains a pool of up to 10 open connections. Under heavy concurrency, you can raise the default connection's pool size with DB_MAX_CONNECTIONS, keeping the combined total across all application instances below your database server's connection limit:

1DB_MAX_CONNECTIONS=20
1DB_MAX_CONNECTIONS=20

For additional connections, chain max_connections on ConnectionConfig, as shown on reporting above. Queries wait up to 30 seconds to acquire a connection from the pool before returning an error. To adjust pool timeouts, call acquire_timeout, idle_timeout, or max_lifetime on ConnectionConfig, such as .acquire_timeout(5.seconds()).

Laravel opens connection pools lazily on the first query, so an unreachable database does not prevent your application from booting unless your own boot hooks query it.

To run a query on a named connection, see Using multiple connections.

Time precision

By default, each database connection stores timestamps, date-times, and times with microsecond precision (6 fractional digits of seconds), matching the maximum precision supported by PostgreSQL and MySQL. Before sending a time value to the database, 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 laravel::now() is never rounded forward into the future, so a query for records up to laravel::now() always finds it.

To store whole seconds instead, or any other precision from 0 to 6, set DB_TIME_PRECISION in your .env file:

1DB_TIME_PRECISION=0
1DB_TIME_PRECISION=0

For additional connections, chain time_precision on ConnectionConfig in src/config/database.rs:

1database.add_connection(
2 "legacy",
3 ConnectionConfig::new("mysql://[email protected]/legacy").time_precision(0),
4);
1database.add_connection(
2 "legacy",
3 ConnectionConfig::new("mysql://[email protected]/legacy").time_precision(0),
4);

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

For TLS, Unix sockets, or other settings that don't fit in a URL, build the connection in src/config/database.rs from SQLx's options for your driver. initialize runs SQL each time the pool opens a new connection:

1use laravel::config::database::{ConnectionConfig, Database};
2use laravel::config::{self, Env};
3use laravel::db::sqlx::postgres::{PgConnectOptions, PgSslMode};
4 
5#[config::section]
6fn database(env: &Env) -> Database {
7 let mut database = Database::from_env(env);
8 
9 let postgres = ConnectionConfig::postgres(
10 PgConnectOptions::new()
11 .host("db.internal")
12 .username("app")
13 .database("app")
14 .ssl_mode(PgSslMode::Require),
15 )
16 .initialize("SET search_path TO app, public");
17 
18 database.add_connection("postgres", postgres);
19 
20 database
21}
1use laravel::config::database::{ConnectionConfig, Database};
2use laravel::config::{self, Env};
3use laravel::db::sqlx::postgres::{PgConnectOptions, PgSslMode};
4 
5#[config::section]
6fn database(env: &Env) -> Database {
7 let mut database = Database::from_env(env);
8 
9 let postgres = ConnectionConfig::postgres(
10 PgConnectOptions::new()
11 .host("db.internal")
12 .username("app")
13 .database("app")
14 .ssl_mode(PgSslMode::Require),
15 )
16 .initialize("SET search_path TO app, public");
17 
18 database.add_connection("postgres", postgres);
19 
20 database
21}

ConnectionConfig::mysql, ConnectionConfig::mariadb, and ConnectionConfig::sqlite accept the same builder options. When replacing the default connection with driver options, chain max_connections or time_precision directly on the ConnectionConfig if you need a custom pool size or time precision.

Running queries

Once your connection is configured, you may run queries with the db::query! macro. Write your SQL as usual, and wrap any Rust variable in braces. The macro binds each one as a query parameter, so a variable 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:

1use laravel::db;
2use laravel::prelude::*;
3 
4pub async fn show(Params(id): Params<i64>) -> laravel::Result<String> {
5 let user = db::query!("SELECT id, name FROM users WHERE id = {id}")
6 .select_one()
7 .await?
8 .or_abort(404)?;
9 
10 let name: String = user.try_get("name")?;
11 
12 Ok(name)
13}
1use laravel::db;
2use laravel::prelude::*;
3 
4pub async fn show(Params(id): Params<i64>) -> laravel::Result<String> {
5 let user = db::query!("SELECT id, name FROM users WHERE id = {id}")
6 .select_one()
7 .await?
8 .or_abort(404)?;
9 
10 let name: String = user.try_get("name")?;
11 
12 Ok(name)
13}

The macro runs the query on your default connection. It doesn't check the SQL against your schema when you compile, so a misspelled column is an error when the query runs, not a compile error.

Running a select query

select returns every matching row, and select_one returns the first, if there is one. Read a row's columns with try_get, by name or by zero-based position:

1use laravel::db;
2 
3let active = true;
4 
5let users = db::query!("SELECT id, name FROM users WHERE active = {active}")
6 .select()
7 .await?;
8 
9for user in users {
10 let name: String = user.try_get("name")?;
11}
1use laravel::db;
2 
3let active = true;
4 
5let users = db::query!("SELECT id, name FROM users WHERE active = {active}")
6 .select()
7 .await?;
8 
9for user in users {
10 let name: String = user.try_get("name")?;
11}

Most of the time you'll want rows as structs instead, as Mapping rows to structs shows. When a query returns a single value, such as a count, scalar returns it directly. It returns None when there's no row:

1let count = db::query!("SELECT COUNT(*) FROM users").scalar::<i64>().await?.unwrap_or(0);
1let count = db::query!("SELECT COUNT(*) FROM users").scalar::<i64>().await?.unwrap_or(0);

When calling a stored procedure that returns multiple result sets, use select_result_sets to collect each set in order and read its rows:

1let account_id = 42;
2 
3let sets = db::query!("CALL account_summary({account_id})")
4 .select_result_sets()
5 .await?;
6 
7for row in &sets[0].rows {
8 let balance: i64 = row.try_get("balance")?;
9}
10 
11for row in &sets[1].rows {
12 let invoice_id: i64 = row.try_get("id")?;
13}
1let account_id = 42;
2 
3let sets = db::query!("CALL account_summary({account_id})")
4 .select_result_sets()
5 .await?;
6 
7for row in &sets[0].rows {
8 let balance: i64 = row.try_get("balance")?;
9}
10 
11for row in &sets[1].rows {
12 let invoice_id: i64 = row.try_get("id")?;
13}

Running insert, update, and delete statements

Use the insert, update, and delete methods to execute write statements against the database. Both update and delete return the number of rows affected by the query:

1use laravel::db;
2 
3let (name, email) = ("Taylor", "[email protected]");
4 
5db::query!("INSERT INTO users (name, email) VALUES ({name}, {email})")
6 .insert()
7 .await?;
8 
9let updated = db::query!("UPDATE users SET votes = 100 WHERE name = {name}")
10 .update()
11 .await?;
12 
13let deleted = db::query!("DELETE FROM users WHERE votes < 10").delete().await?;
1use laravel::db;
2 
3let (name, email) = ("Taylor", "[email protected]");
4 
5db::query!("INSERT INTO users (name, email) VALUES ({name}, {email})")
6 .insert()
7 .await?;
8 
9let updated = db::query!("UPDATE users SET votes = 100 WHERE name = {name}")
10 .update()
11 .await?;
12 
13let deleted = db::query!("DELETE FROM users WHERE votes < 10").delete().await?;

To get the new row's ID back, see Returning inserted IDs and rows. For statements that return nothing, such as DROP TABLE, use statement:

1db::query!("DROP TABLE users").statement().await?;
1db::query!("DROP TABLE users").statement().await?;

To run multiple statements separated by semicolons, use unprepared. Because it sends the SQL directly as written without preparing it, it cannot bind values and returns an error if the query contains any captured variables:

1db::query!(
2 "CREATE TABLE audit_logs (id INTEGER PRIMARY KEY, message TEXT);
3 CREATE INDEX audit_logs_message_index ON audit_logs (message);"
4)
5.unprepared()
6.await?;
1db::query!(
2 "CREATE TABLE audit_logs (id INTEGER PRIMARY KEY, message TEXT);
3 CREATE INDEX audit_logs_message_index ON audit_logs (message);"
4)
5.unprepared()
6.await?;

Binding values

A capture may name a variable or a field, such as {email}, {user.id}, or {form.address.city}. The macro borrows each one, so you can keep using your variables afterward. It accepts only names and fields, so compute anything else, such as a method call, into a variable first.

To match against a list, spread a Vec, array, or slice with {...name}. It binds one parameter per item:

1use laravel::db;
2 
3let roles = vec!["admin", "editor"];
4 
5let users = db::query!("SELECT * FROM users WHERE role IN ({...roles})")
6 .select()
7 .await?;
1use laravel::db;
2 
3let roles = vec!["admin", "editor"];
4 
5let users = db::query!("SELECT * FROM users WHERE role IN ({...roles})")
6 .select()
7 .await?;

An empty list returns an error without running the query, so check for one first when the list comes from input. Place captures outside SQL quotes and comments, and write a literal brace as {{ or }}.

Inserting many rows

To insert a collection in one statement, expand it with {...users(name, email)}. The expansion writes one parenthesized row per item, binding the fields you list:

1use laravel::db;
2 
3struct NewUser {
4 name: String,
5 email: String,
6}
7 
8let users = vec![
9 NewUser { name: "Taylor".into(), email: "[email protected]".into() },
10 NewUser { name: "Jess".into(), email: "[email protected]".into() },
11];
12 
13let inserted = db::query!("INSERT INTO users (name, email) VALUES {...users(name, email)}")
14 .insert()
15 .await?;
16 
17let count = inserted.rows_affected();
1use laravel::db;
2 
3struct NewUser {
4 name: String,
5 email: String,
6}
7 
8let users = vec![
9 NewUser { name: "Taylor".into(), email: "[email protected]".into() },
10 NewUser { name: "Jess".into(), email: "[email protected]".into() },
11];
12 
13let inserted = db::query!("INSERT INTO users (name, email) VALUES {...users(name, email)}")
14 .insert()
15 .await?;
16 
17let count = inserted.rows_affected();

Put the expansion directly after VALUES, without parentheses around it. Each field is a parameter, and PostgreSQL and MySQL allow 65,535 parameters in one query, while SQLite allows 32,766. Insert a larger collection in chunks.

Mapping rows to structs

To map rows into your own structs, derive db::FromRow and call select_as or select_one_as. Fields map to columns by name, and #[db(rename = "...")] maps a field to a column with another name:

1use laravel::db;
2 
3#[derive(Debug, db::FromRow)]
4struct Subscriber {
5 id: i64,
6 #[db(rename = "email_address")]
7 email: String,
8 nickname: Option<String>,
9}
10 
11let id = 42;
12 
13let subscriber: Option<Subscriber> =
14 db::query!("SELECT id, email_address, nickname FROM subscribers WHERE id = {id}")
15 .select_one_as()
16 .await?;
17 
18let subscribers = db::query!("SELECT id, email_address, nickname FROM subscribers")
19 .select_as::<Subscriber>()
20 .await?;
1use laravel::db;
2 
3#[derive(Debug, db::FromRow)]
4struct Subscriber {
5 id: i64,
6 #[db(rename = "email_address")]
7 email: String,
8 nickname: Option<String>,
9}
10 
11let id = 42;
12 
13let subscriber: Option<Subscriber> =
14 db::query!("SELECT id, email_address, nickname FROM subscribers WHERE id = {id}")
15 .select_one_as()
16 .await?;
17 
18let subscribers = db::query!("SELECT id, email_address, nickname FROM subscribers")
19 .select_as::<Subscriber>()
20 .await?;

Mapping ignores extra columns. A missing column, or a NULL in a field that isn't an Option, returns an error. To read one column from every row, map each row to the column's type:

1let ids = db::query!("SELECT id FROM users WHERE active").select_as::<i64>().await?;
1let ids = db::query!("SELECT id FROM users WHERE active").select_as::<i64>().await?;

#[db(json)] decodes a JSON column into any field that implements Deserialize. On an Option field, both SQL NULL and JSON null read as None:

1#[derive(db::FromRow)]
2struct User {
3 id: i64,
4 #[db(json)]
5 roles: Vec<String>,
6 #[db(json)]
7 preferences: Option<serde_json::Value>,
8}
1#[derive(db::FromRow)]
2struct User {
3 id: i64,
4 #[db(json)]
5 roles: Vec<String>,
6 #[db(json)]
7 preferences: Option<serde_json::Value>,
8}

To map a column into a single-field wrapper struct, derive Newtype, which the prelude imports. The struct then binds and decodes as the value it wraps, so it works as a FromRow field and as a model column:

1use laravel::db;
2use laravel::prelude::*;
3 
4#[derive(Debug, Newtype)]
5struct Email(String);
6 
7#[derive(Debug, db::FromRow)]
8struct Subscriber {
9 id: i64,
10 email: Email,
11}
1use laravel::db;
2use laravel::prelude::*;
3 
4#[derive(Debug, Newtype)]
5struct Email(String);
6 
7#[derive(Debug, db::FromRow)]
8struct Subscriber {
9 id: i64,
10 email: Email,
11}

For custom conversions, such as parsing an IANA timezone name from a text column into a TimeZone, implement db::Decode. index is the column's zero-based position in the row, which you can pass to row.try_get to read the underlying database value:

1use laravel::db::{AnyRow, Decode};
2use laravel::time::tz::TimeZone;
3 
4struct UserTimeZone(TimeZone);
5 
6impl Decode for UserTimeZone {
7 fn decode(row: &AnyRow, index: usize) -> laravel::Result<Self> {
8 let name: String = row.try_get(index)?;
9 
10 Ok(Self(TimeZone::get(&name)?))
11 }
12}
1use laravel::db::{AnyRow, Decode};
2use laravel::time::tz::TimeZone;
3 
4struct UserTimeZone(TimeZone);
5 
6impl Decode for UserTimeZone {
7 fn decode(row: &AnyRow, index: usize) -> laravel::Result<Self> {
8 let name: String = row.try_get(index)?;
9 
10 Ok(Self(TimeZone::get(&name)?))
11 }
12}

Returning inserted IDs and rows

To retrieve the ID of a newly inserted row, call insert_returning_id. Include a RETURNING id clause on PostgreSQL and SQLite; on MySQL and MariaDB, omit the clause and Laravel automatically reads the auto-increment ID:

1use laravel::db;
2 
3let name = "Taylor";
4 
5let id: Option<i64> = db::query!("INSERT INTO users (name) VALUES ({name}) RETURNING id")
6 .insert_returning_id()
7 .await?;
1use laravel::db;
2 
3let name = "Taylor";
4 
5let id: Option<i64> = db::query!("INSERT INTO users (name) VALUES ({name}) RETURNING id")
6 .insert_returning_id()
7 .await?;

To get whole rows back from a write, write a RETURNING clause and use one of the returning methods. The _as methods map the rows with db::FromRow:

1#[derive(db::FromRow)]
2struct User {
3 id: i64,
4 name: String,
5}
6 
7let (id, name) = (42, "Taylor Otwell");
8 
9let user = db::query!("UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name")
10 .update_returning_as::<User>()
11 .await?;
1#[derive(db::FromRow)]
2struct User {
3 id: i64,
4 name: String,
5}
6 
7let (id, name) = (42, "Taylor Otwell");
8 
9let user = db::query!("UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name")
10 .update_returning_as::<User>()
11 .await?;
Statement First row, as Option<T> Every row, as Vec<T>
INSERT insert_returning_as insert_returning_all_as
UPDATE update_returning_as update_returning_all_as
DELETE delete_returning_as delete_returning_all_as

Each method also has a raw variant without the _as suffix, such as insert_returning or update_returning_all, which returns AnyRow values you can read with try_get:

1if let Some(row) = db::query!(
2 "UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name"
3)
4.update_returning()
5.await?
6{
7 let updated_name: String = row.try_get("name")?;
8}
1if let Some(row) = db::query!(
2 "UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name"
3)
4.update_returning()
5.await?
6{
7 let updated_name: String = row.try_get("name")?;
8}

PostgreSQL and SQLite support RETURNING on INSERT, UPDATE, and DELETE, MariaDB supports it on INSERT and DELETE, and MySQL does not support RETURNING.

JSON columns

To store a custom Rust type as JSON, derive db::Json alongside Serde's traits. Bind it in queries as a standard parameter and read it back with try_get or as a FromRow field:

1use laravel::db;
2use laravel::prelude::*;
3use serde::{Deserialize, Serialize};
4 
5#[derive(Serialize, Deserialize, db::Json)]
6struct Preferences {
7 theme: String,
8 notifications: bool,
9}
10 
11let id = 42;
12let preferences = Preferences { theme: "dark".into(), notifications: true };
13 
14db::query!("UPDATE users SET preferences = {preferences} WHERE id = {id}")
15 .update()
16 .await?;
17 
18let row = db::query!("SELECT preferences FROM users WHERE id = {id}")
19 .select_one()
20 .await?
21 .or_abort(404)?;
22 
23let preferences: Preferences = row.try_get("preferences")?;
1use laravel::db;
2use laravel::prelude::*;
3use serde::{Deserialize, Serialize};
4 
5#[derive(Serialize, Deserialize, db::Json)]
6struct Preferences {
7 theme: String,
8 notifications: bool,
9}
10 
11let id = 42;
12let preferences = Preferences { theme: "dark".into(), notifications: true };
13 
14db::query!("UPDATE users SET preferences = {preferences} WHERE id = {id}")
15 .update()
16 .await?;
17 
18let row = db::query!("SELECT preferences FROM users WHERE id = {id}")
19 .select_one()
20 .await?
21 .or_abort(404)?;
22 
23let preferences: Preferences = row.try_get("preferences")?;

A Vec or other collection captured as {roles} binds as a single JSON value, while {...roles} spreads it into one parameter per item. PostgreSQL and MySQL store JSON in native JSON columns, and SQLite stores it as text.

Enums, UUIDs, and IP addresses

To store an enum without fields as text, derive Enum, which the prelude imports. It uses the same names as Serde, so #[serde(rename_all)] and #[serde(rename)] decide what's stored:

1use laravel::db;
2use laravel::prelude::*;
3use serde::{Deserialize, Serialize};
4 
5#[derive(Serialize, Deserialize, Enum)]
6#[serde(rename_all = "snake_case")]
7enum Status {
8 PendingReview,
9 Active,
10}
11 
12let id = 42;
13let status = Status::PendingReview;
14 
15db::query!("UPDATE posts SET status = {status} WHERE id = {id}")
16 .update()
17 .await?;
1use laravel::db;
2use laravel::prelude::*;
3use serde::{Deserialize, Serialize};
4 
5#[derive(Serialize, Deserialize, Enum)]
6#[serde(rename_all = "snake_case")]
7enum Status {
8 PendingReview,
9 Active,
10}
11 
12let id = 42;
13let status = Status::PendingReview;
14 
15db::query!("UPDATE posts SET status = {status} WHERE id = {id}")
16 .update()
17 .await?;

This stores pending_review. Reading a string that matches no variant returns an error. For enums whose variants hold data, derive db::Json instead and store them in a JSON column such as table.json("payment_method") or table.jsonb("payment_method"):

1use laravel::db;
2use serde::{Deserialize, Serialize};
3 
4#[derive(Serialize, Deserialize, db::Json)]
5enum PaymentMethod {
6 Card { last4: String },
7 BankTransfer,
8}
9 
10let id = 42;
11let method = PaymentMethod::Card { last4: "4242".into() };
12 
13db::query!("UPDATE orders SET payment_method = {method} WHERE id = {id}")
14 .update()
15 .await?;
1use laravel::db;
2use serde::{Deserialize, Serialize};
3 
4#[derive(Serialize, Deserialize, db::Json)]
5enum PaymentMethod {
6 Card { last4: String },
7 BankTransfer,
8}
9 
10let id = 42;
11let method = PaymentMethod::Card { last4: "4242".into() };
12 
13db::query!("UPDATE orders SET payment_method = {method} WHERE id = {id}")
14 .update()
15 .await?;

For UUIDs and ULIDs, use laravel::str::Uuid and laravel::str::Ulid. A Uuid binds as a native UUID on PostgreSQL and as text on other databases, and a Ulid always binds as text. IpAddr binds as text too, so store it in a text column, as the schema builder's ip_address column does:

1use std::net::IpAddr;
2 
3use laravel::db;
4use laravel::str::{self, Ulid, Uuid};
5 
6let id: Uuid = str::uuid();
7let trace_id: Ulid = str::ulid();
8let ip_address: IpAddr = "203.0.113.7".parse()?;
9 
10db::query!(
11 "INSERT INTO logins (id, trace_id, ip_address) VALUES ({id}, {trace_id}, {ip_address})"
12)
13.insert()
14.await?;
1use std::net::IpAddr;
2 
3use laravel::db;
4use laravel::str::{self, Ulid, Uuid};
5 
6let id: Uuid = str::uuid();
7let trace_id: Ulid = str::ulid();
8let ip_address: IpAddr = "203.0.113.7".parse()?;
9 
10db::query!(
11 "INSERT INTO logins (id, trace_id, ip_address) VALUES ({id}, {trace_id}, {ip_address})"
12)
13.insert()
14.await?;

Dates and timestamps

Dates and times use the types in laravel::time:

1use laravel::db;
2use laravel::prelude::*;
3use laravel::time::Timestamp;
4use laravel::time::civil::Date;
5 
6let id = 42;
7let ships_on: Date = "2026-11-20".parse()?;
8let paid_at = laravel::now().timestamp();
9 
10db::query!("UPDATE orders SET ships_on = {ships_on}, paid_at = {paid_at} WHERE id = {id}")
11 .update()
12 .await?;
13 
14let order = db::query!("SELECT ships_on, paid_at FROM orders WHERE id = {id}")
15 .select_one()
16 .await?
17 .or_abort(404)?;
18 
19let paid_at: Option<Timestamp> = order.try_get("paid_at")?;
1use laravel::db;
2use laravel::prelude::*;
3use laravel::time::Timestamp;
4use laravel::time::civil::Date;
5 
6let id = 42;
7let ships_on: Date = "2026-11-20".parse()?;
8let paid_at = laravel::now().timestamp();
9 
10db::query!("UPDATE orders SET ships_on = {ships_on}, paid_at = {paid_at} WHERE id = {id}")
11 .update()
12 .await?;
13 
14let order = db::query!("SELECT ships_on, paid_at FROM orders WHERE id = {id}")
15 .select_one()
16 .await?
17 .or_abort(404)?;
18 
19let paid_at: Option<Timestamp> = order.try_get("paid_at")?;
Rust type What it holds PostgreSQL MySQL SQLite
time::civil::Date A calendar date DATE DATE Text
time::civil::Time A time of day TIME TIME Text
time::civil::DateTime A date and time, without a timezone TIMESTAMP DATETIME Text
time::Timestamp An instant TIMESTAMPTZ or TIMESTAMP TIMESTAMP or DATETIME Text

Laravel stores times in UTC, so a Timestamp field reads the schema builder's timestamps() columns on every database, even though some of those columns have no timezone.

Decimals

For exact decimals such as prices or account balances, use laravel::numeric::Decimal rather than floating-point numbers:

1use laravel::db;
2use laravel::numeric::Decimal;
3use laravel::prelude::*;
4 
5let id = 42;
6let subtotal: Decimal = "149.99".parse()?;
7let tax: Decimal = "12.37".parse()?;
8let total = (&subtotal + &tax).round(2);
9 
10db::query!("UPDATE orders SET total = {total} WHERE id = {id}")
11 .update()
12 .await?;
13 
14let order = db::query!("SELECT total FROM orders WHERE id = {id}")
15 .select_one()
16 .await?
17 .or_abort(404)?;
18 
19let total: Decimal = order.try_get("total")?;
1use laravel::db;
2use laravel::numeric::Decimal;
3use laravel::prelude::*;
4 
5let id = 42;
6let subtotal: Decimal = "149.99".parse()?;
7let tax: Decimal = "12.37".parse()?;
8let total = (&subtotal + &tax).round(2);
9 
10db::query!("UPDATE orders SET total = {total} WHERE id = {id}")
11 .update()
12 .await?;
13 
14let order = db::query!("SELECT total FROM orders WHERE id = {id}")
15 .select_one()
16 .await?
17 .or_abort(404)?;
18 
19let total: Decimal = order.try_get("total")?;

Decimal supports standard arithmetic (+, -, *, /), comparisons, and rounding helpers such as .round(2) and .with_scale(2). Borrow operands like &subtotal + &tax when you want to reuse them afterward.

Decimal maps to NUMERIC on PostgreSQL, DECIMAL on MySQL, and NUMERIC or text on SQLite. Parse decimals from strings rather than floats so they preserve every digit. Because SQLite has no native exact decimal type and stores fractional NUMERIC values as floating-point numbers (roughly 15 digits of precision), 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, call each with an async closure; iteration stops immediately on the first error:

1use laravel::db;
2 
3db::query!("SELECT email FROM subscribers").each(async |row| {
4 let email: String = row.try_get("email")?;
5 
6 // Send the newsletter...
7 
8 Ok(())
9}).await?;
1use laravel::db;
2 
3db::query!("SELECT email FROM subscribers").each(async |row| {
4 let email: String = row.try_get("email")?;
5 
6 // Send the newsletter...
7 
8 Ok(())
9}).await?;

each keeps a connection from the pool until it finishes, so keep slow work out of the closure. The closure can't change variables outside it. To collect rows, keep a running total, or stop early, use cursor, which returns a stream of rows:

1use laravel::db;
2use laravel::stream::TryStreamExt;
3 
4let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id").cursor();
5let mut sent = 0;
6 
7while let Some(row) = cursor.try_next().await? {
8 let email: String = row.try_get("email")?;
9 
10 // Send the newsletter...
11 
12 sent += 1;
13}
1use laravel::db;
2use laravel::stream::TryStreamExt;
3 
4let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id").cursor();
5let mut sent = 0;
6 
7while let Some(row) = cursor.try_next().await? {
8 let email: String = row.try_get("email")?;
9 
10 // Send the newsletter...
11 
12 sent += 1;
13}

To map each streamed row directly into a struct deriving db::FromRow, use cursor_as:

1use laravel::db;
2use laravel::stream::TryStreamExt;
3 
4#[derive(db::FromRow)]
5struct Subscriber {
6 id: i64,
7 email: String,
8}
9 
10let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id")
11 .cursor_as::<Subscriber>();
12 
13while let Some(subscriber) = cursor.try_next().await? {
14 tracing::info!(id = subscriber.id, email = %subscriber.email, "Processing subscriber");
15}
1use laravel::db;
2use laravel::stream::TryStreamExt;
3 
4#[derive(db::FromRow)]
5struct Subscriber {
6 id: i64,
7 email: String,
8}
9 
10let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id")
11 .cursor_as::<Subscriber>();
12 
13while let Some(subscriber) = cursor.try_next().await? {
14 tracing::info!(id = subscriber.id, email = %subscriber.email, "Processing subscriber");
15}

Handling errors

Query failures return standard laravel::Error values, so propagating them with ? from a handler produces a 500 response. Each error message includes the database error, connection name, driver, and SQL query, such as no such table: subscribers (Connection: primary, Driver: SQLite, SQL: INSERT INTO subscribers (email) VALUES (?)). Bound values are omitted from the message, and the error tracks the call site that built the query. To handle specific constraint failures, such as a duplicate email address, inspect the error with db::is_unique_violation:

1use laravel::db;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct Subscribe {
7 #[validate(required, email)]
8 email: String,
9}
10 
11pub async fn subscribe(
12 Valid(Subscribe { email }): Valid<Subscribe>,
13) -> laravel::Result<Redirect> {
14 match db::query!("INSERT INTO subscribers (email) VALUES ({email})").insert().await {
15 Ok(_) => {}
16 Err(error) if db::is_unique_violation(&error) => {
17 // Already subscribed...
18 }
19 Err(error) => return Err(error),
20 }
21 
22 Ok(Redirect::back())
23}
1use laravel::db;
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct Subscribe {
7 #[validate(required, email)]
8 email: String,
9}
10 
11pub async fn subscribe(
12 Valid(Subscribe { email }): Valid<Subscribe>,
13) -> laravel::Result<Redirect> {
14 match db::query!("INSERT INTO subscribers (email) VALUES ({email})").insert().await {
15 Ok(_) => {}
16 Err(error) if db::is_unique_violation(&error) => {
17 // Already subscribed...
18 }
19 Err(error) => return Err(error),
20 }
21 
22 Ok(Redirect::back())
23}

Laravel provides helpers to classify common database errors across PostgreSQL, MySQL, MariaDB, and SQLite:

Helper Matches
db::is_unique_violation(&error) Unique or primary key constraint violation
db::is_foreign_key_violation(&error) Foreign key constraint violation
db::is_check_violation(&error) CHECK constraint violation
db::is_lost_connection(&error) Dropped connection, server restart, or failed-over read-only primary

Transactions

When transferring funds between two accounts, both updates must succeed or fail together. Use db::transaction to run an async closure inside a database transaction on the default connection; Laravel commits automatically when the closure returns Ok and rolls back on error:

1use laravel::db;
2 
3let (from, to, amount) = (1_i64, 2_i64, 25_i64);
4 
5db::transaction(async |tx| {
6 db::query!(tx, "UPDATE accounts SET balance = balance - {amount} WHERE id = {from}")
7 .update()
8 .await?;
9 
10 db::query!(tx, "UPDATE accounts SET balance = balance + {amount} WHERE id = {to}")
11 .update()
12 .await?;
13 
14 Ok(())
15})
16.await?;
1use laravel::db;
2 
3let (from, to, amount) = (1_i64, 2_i64, 25_i64);
4 
5db::transaction(async |tx| {
6 db::query!(tx, "UPDATE accounts SET balance = balance - {amount} WHERE id = {from}")
7 .update()
8 .await?;
9 
10 db::query!(tx, "UPDATE accounts SET balance = balance + {amount} WHERE id = {to}")
11 .update()
12 .await?;
13 
14 Ok(())
15})
16.await?;

The closure may borrow your variables and return a value, which db::transaction returns after the commit:

1let order_id: i64 = db::transaction(async |tx| {
2 let order_id = db::query!(
3 tx,
4 "INSERT INTO orders (user_id, total) VALUES ({user_id}, {total}) RETURNING id"
5 )
6 .insert_returning_id()
7 .await?
8 .expect("inserted order ID");
9 
10 db::query!(tx, "INSERT INTO order_items (order_id, sku) VALUES ({order_id}, {sku})")
11 .insert()
12 .await?;
13 
14 Ok(order_id)
15})
16.await?;
1let order_id: i64 = db::transaction(async |tx| {
2 let order_id = db::query!(
3 tx,
4 "INSERT INTO orders (user_id, total) VALUES ({user_id}, {total}) RETURNING id"
5 )
6 .insert_returning_id()
7 .await?
8 .expect("inserted order ID");
9 
10 db::query!(tx, "INSERT INTO order_items (order_id, sku) VALUES ({order_id}, {sku})")
11 .insert()
12 .await?;
13 
14 Ok(order_id)
15})
16.await?;

To run a transaction on another connection, call transaction on that connection: db::connection("reporting")?.transaction(async |tx| { .. }).

Inside the closure, every query on the transaction's connection joins the transaction, even queries that don't go through tx. A helper function can run a plain db::query! or a model query and still see uncommitted rows, and its writes roll back with yours. The database session, cache, and queue stores, the unique and exists validation rules, and awaited listeners all participate in the active transaction.

Calling db::transaction inside another transaction's closure creates a savepoint. When the inner closure fails, only its writes roll back, and the outer transaction carries on. A function may wrap its own writes in db::transaction, and it works the same whether or not you call it inside your transaction.

A few queries behave differently inside a transaction:

  • A query from a task started with task::spawn fails, because the task could outlive the transaction. Await the work inside the transaction instead, or start it after the commit.
  • To write something that must survive a rollback, such as an audit entry, run it on db::default_connection()?.outside_transaction().
  • On MySQL and SQLite, a query inside an each closure fails, because the cursor holds the transaction's connection. Read the rows with select first.
  • MySQL commits the transaction when it runs 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 cause the database to abort one of them. transaction_with_attempts retries the closure automatically when a deadlock or MySQL/SQLite lock wait timeout occurs, up to the total number of attempts specified:

1use laravel::db;
2 
3let id = 42_i64;
4 
5db::transaction_with_attempts(3, async |tx| {
6 db::query!(tx, "UPDATE accounts SET balance = balance + 1 WHERE id = {id}")
7 .update()
8 .await?;
9 
10 Ok(())
11})
12.await?;
1use laravel::db;
2 
3let id = 42_i64;
4 
5db::transaction_with_attempts(3, async |tx| {
6 db::query!(tx, "UPDATE accounts SET balance = balance + 1 WHERE id = {id}")
7 .update()
8 .await?;
9 
10 Ok(())
11})
12.await?;

Each attempt runs a fresh copy of the closure, so the closure must be Clone. It may borrow your variables, but not change them. Other errors, such as a constraint violation, don't retry. Keep side effects that can't run twice, such as sending an email, out of the closure, and register them as after-commit work instead.

After-commit work

Some work should happen only once the data it describes is committed, such as sending an order confirmation. db::after_commit registers that work from anywhere inside a transaction, without passing the transaction around. This function records an order, and logs it once the order is committed:

1use laravel::db;
2 
3pub async fn place_order(user_id: i64, total: i64) -> laravel::Result<()> {
4 db::query!("INSERT INTO orders (user_id, total) VALUES ({user_id}, {total})")
5 .insert()
6 .await?;
7 
8 db::after_commit(async move || {
9 tracing::info!(user_id, "Order placed");
10 
11 Ok(())
12 })
13 .await
14}
15 
16db::transaction(async |_| place_order(1, 4_999).await).await?;
1use laravel::db;
2 
3pub async fn place_order(user_id: i64, total: i64) -> laravel::Result<()> {
4 db::query!("INSERT INTO orders (user_id, total) VALUES ({user_id}, {total})")
5 .insert()
6 .await?;
7 
8 db::after_commit(async move || {
9 tracing::info!(user_id, "Order placed");
10 
11 Ok(())
12 })
13 .await
14}
15 
16db::transaction(async |_| place_order(1, 4_999).await).await?;

When no transaction is active, the callback runs immediately. If the transaction rolls back, Laravel discards it. Inside a nested savepoint, the callback waits until the outermost transaction commits.

The callback runs after the connection is released, so it may query the committed data. Its closure must own what it captures, which is why the example uses async move. If the callback fails, db::transaction returns an AfterCommitError, while the committed data remains saved.

After-commit callbacks are held in memory, so they are lost if the process stops before they run. For durable follow-up work, dispatch a queued job instead. Jobs dispatched inside a transaction automatically wait for the commit, and so do events, except for listeners marked at_dispatch.

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 db::begin, or begin on a connection. Calling begin on a transaction creates a savepoint:

1use laravel::db;
2 
3let mut transaction = db::begin().await?;
4 
5db::query!(transaction, "INSERT INTO notes (body) VALUES ('Keep this note')")
6 .insert()
7 .await?;
8 
9let mut savepoint = transaction.begin().await?;
10 
11db::query!(savepoint, "INSERT INTO notes (body) VALUES ('Discard this note')")
12 .insert()
13 .await?;
14 
15savepoint.rollback().await?;
16 
17transaction.commit().await?;
1use laravel::db;
2 
3let mut transaction = db::begin().await?;
4 
5db::query!(transaction, "INSERT INTO notes (body) VALUES ('Keep this note')")
6 .insert()
7 .await?;
8 
9let mut savepoint = transaction.begin().await?;
10 
11db::query!(savepoint, "INSERT INTO notes (body) VALUES ('Discard this note')")
12 .insert()
13 .await?;
14 
15savepoint.rollback().await?;
16 
17transaction.commit().await?;

Dropping a transaction you haven't committed rolls it back. Queries that don't go through the transaction, and db::after_commit, join it only inside transaction.scope(async |tx| { .. }).

Using multiple connections

db::query! runs on your default connection. To run a query on another, look the connection up by name with db::connection and pass it before the SQL:

1use laravel::db;
2 
3let reporting = db::connection("reporting")?;
4let month = "2026-10";
5 
6let totals = db::query!(
7 reporting,
8 "SELECT region, SUM(total) FROM sales WHERE month = {month} GROUP BY region"
9)
10.select()
11.await?;
1use laravel::db;
2 
3let reporting = db::connection("reporting")?;
4let month = "2026-10";
5 
6let totals = db::query!(
7 reporting,
8 "SELECT region, SUM(total) FROM sales WHERE month = {month} GROUP BY region"
9)
10.select()
11.await?;

db::default_connection() returns the default connection. Connection handles are cheap to clone and do not open a pool until the first query runs. Because Laravel does not translate raw SQL across database engines, you can match on connection.driver() when writing database-specific SQL:

1use laravel::db::{self, Driver};
2 
3let connection = db::default_connection()?;
4 
5let version = match connection.driver() {
6 Driver::Postgres => db::query!(connection, "SELECT version()")
7 .scalar::<String>()
8 .await?,
9 Driver::MySql | Driver::MariaDb => db::query!(connection, "SELECT VERSION()")
10 .scalar::<String>()
11 .await?,
12 Driver::Sqlite => db::query!(connection, "SELECT sqlite_version()")
13 .scalar::<String>()
14 .await?,
15};
1use laravel::db::{self, Driver};
2 
3let connection = db::default_connection()?;
4 
5let version = match connection.driver() {
6 Driver::Postgres => db::query!(connection, "SELECT version()")
7 .scalar::<String>()
8 .await?,
9 Driver::MySql | Driver::MariaDb => db::query!(connection, "SELECT VERSION()")
10 .scalar::<String>()
11 .await?,
12 Driver::Sqlite => db::query!(connection, "SELECT sqlite_version()")
13 .scalar::<String>()
14 .await?,
15};

Scoped default connections

Some applications keep each tenant in its own database, so every query in a request must go to that tenant's connection. db::using_connection changes the default connection while a future runs, for every query inside it, including the query builder's and your models':

1use laravel::db;
2 
3db::using_connection("tenant_42", async {
4 let count = db::query!("SELECT COUNT(*) FROM projects").scalar::<i64>().await?;
5 
6 // ...
7 
8 Ok::<_, laravel::Error>(())
9})
10.await?;
1use laravel::db;
2 
3db::using_connection("tenant_42", async {
4 let count = db::query!("SELECT COUNT(*) FROM projects").scalar::<i64>().await?;
5 
6 // ...
7 
8 Ok::<_, laravel::Error>(())
9})
10.await?;

The default goes back to the previous one when the future finishes. Tasks you start with task::spawn inherit the override, but raw Tokio tasks don't.

Adding connections at runtime

You can register and remove named connections at runtime by injecting DatabaseManager. Calling add_connection registers a connection lazily without opening its pool until the first query runs, and remove_connection unregisters it and closes its pool once active queries finish:

1use laravel::config::database::ConnectionConfig;
2use laravel::container::Inject;
3use laravel::db::DatabaseManager;
4 
5pub async fn connect_shard(database: Inject<DatabaseManager>, shard: &str, url: String) {
6 database.add_connection(shard, ConnectionConfig::new(url));
7}
8 
9pub async fn disconnect_shard(database: Inject<DatabaseManager>, shard: &str) {
10 database.remove_connection(shard);
11}
1use laravel::config::database::ConnectionConfig;
2use laravel::container::Inject;
3use laravel::db::DatabaseManager;
4 
5pub async fn connect_shard(database: Inject<DatabaseManager>, shard: &str, url: String) {
6 database.add_connection(shard, ConnectionConfig::new(url));
7}
8 
9pub async fn disconnect_shard(database: Inject<DatabaseManager>, shard: &str) {
10 database.remove_connection(shard);
11}

Registered connections remain in DatabaseManager until removed, so keep the number of named connections bounded. For one-off or temporary connections, such as importing from a customer-supplied database, call database.connect instead to create an unregistered connection whose pool closes automatically when the handle drops:

1use laravel::config::database::ConnectionConfig;
2use laravel::container::Inject;
3use laravel::db::{self, DatabaseManager};
4 
5pub async fn import_from(
6 database: Inject<DatabaseManager>,
7 url: String,
8) -> laravel::Result<i64> {
9 let external = database.connect(ConnectionConfig::new(url))?;
10 
11 let count = db::query!(external, "SELECT COUNT(*) FROM customers")
12 .scalar::<i64>()
13 .await?
14 .unwrap_or(0);
15 
16 Ok(count)
17}
1use laravel::config::database::ConnectionConfig;
2use laravel::container::Inject;
3use laravel::db::{self, DatabaseManager};
4 
5pub async fn import_from(
6 database: Inject<DatabaseManager>,
7 url: String,
8) -> laravel::Result<i64> {
9 let external = database.connect(ConnectionConfig::new(url))?;
10 
11 let count = db::query!(external, "SELECT COUNT(*) FROM customers")
12 .scalar::<i64>()
13 .await?
14 .unwrap_or(0);
15 
16 Ok(count)
17}

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 your replicas' hosts in DB_READ_HOSTS, separated by commas:

1DATABASE_URL=postgres://app:[email protected]/app
2DB_READ_HOSTS=replica-1.internal,replica-2.internal:5433
3DB_STICKY=true
1DATABASE_URL=postgres://app:[email protected]/app
2DB_READ_HOSTS=replica-1.internal,replica-2.internal:5433
3DB_STICKY=true

Each replica connects with DATABASE_URL's credentials, database, and options, and changes only the host, and the port when you give one. Laravel picks a replica at random for each new connection.

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:

1DATABASE_URL=postgres://app:[email protected]/app
2DB_READ_HOSTS=replica-1.internal,postgres://reader:[email protected]/app
1DATABASE_URL=postgres://app:[email protected]/app
2DB_READ_HOSTS=replica-1.internal,postgres://reader:[email protected]/app

If 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:

1DATABASE_URL=postgres://app:[email protected]/app
2DB_WRITE_URL=postgres://app:[email protected]/app
3DB_READ_HOSTS=reader-1.db.internal,reader-2.db.internal
1DATABASE_URL=postgres://app:[email protected]/app
2DB_WRITE_URL=postgres://app:[email protected]/app
3DB_READ_HOSTS=reader-1.db.internal,reader-2.db.internal

Every URL on a connection must use the same database driver, so you can't pair a PostgreSQL writer with MySQL replicas. Tests that refresh the database still create their databases from DATABASE_URL.

These variables configure the default connection. To give another connection replicas, or to configure them in code, give the connection a read endpoint, and optionally a write endpoint, in src/config/database.rs:

1use laravel::config::database::{ConnectionConfig, Endpoint};
2 
3database.add_connection(
4 "reporting",
5 ConnectionConfig::new("postgres://app:password@reporting/app")
6 .read(Endpoint::hosts(["reporting-replica-1", "reporting-replica-2"]))
7 .sticky(true),
8);
1use laravel::config::database::{ConnectionConfig, Endpoint};
2 
3database.add_connection(
4 "reporting",
5 ConnectionConfig::new("postgres://app:password@reporting/app")
6 .read(Endpoint::hosts(["reporting-replica-1", "reporting-replica-2"]))
7 .sticky(true),
8);

Endpoint::hosts keeps the connection's credentials, database, and options, and changes only the host. To connect with other credentials, use Endpoint::new(url) instead. To read a list in the same format as DB_READ_HOSTS from a variable of your own, use env.get::<Endpoint>("REPORTING_READ_HOSTS").

When you configure the default connection in code and call apply_env, each of these variables that's set replaces the setting it names, and the connection keeps the settings whose variables aren't set.

Laravel routes each query by the method that runs it. select, select_one, scalar, and cursors read from a replica. Writes, the returning methods, and every query in a transaction use the writer: 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 writer. With sticky enabled, once a request, queued job, or console command writes to the connection, subsequent reads use the writer for the remainder of that request, job, or command so it always reads its own writes. To force a single query onto the writer, such as reading a row written by another request, call use_write_connection:

1use laravel::db;
2 
3let id = 42_i64;
4 
5let order = db::query!("SELECT * FROM orders WHERE id = {id}")
6 .use_write_connection()
7 .select_one()
8 .await?;
1use laravel::db;
2 
3let id = 42_i64;
4 
5let order = db::query!("SELECT * FROM orders WHERE id = {id}")
6 .use_write_connection()
7 .select_one()
8 .await?;

To send every read to the writer for the rest of the request, call use_write_connection_when_reading(true) on the connection.

Preventing stale reads across requests

If a user updates a post and then reloads the page, a read replica may still show the old title. The sticky option ends when the update request ends. To send the user's next requests to the writer while replicas catch up, append PreventStaleDatabaseReads to the web middleware group in src/app.rs:

1use laravel::http::middleware::PreventStaleDatabaseReads;
2 
3.with_middleware(|middleware, _| {
4 middleware.web(|web| {
5 web.append(PreventStaleDatabaseReads::default());
6 });
7})
1use laravel::http::middleware::PreventStaleDatabaseReads;
2 
3.with_middleware(|middleware, _| {
4 middleware.web(|web| {
5 web.append(PreventStaleDatabaseReads::default());
6 });
7})

For two seconds after a write to the default connection, the middleware sends reads on that connection to the writer for requests in the same session. If your replicas need more time, pass a duration instead:

1use laravel::time::ToSpan;
2 
3web.append(PreventStaleDatabaseReads::new(5.seconds()));
1use laravel::time::ToSpan;
2 
3web.append(PreventStaleDatabaseReads::new(5.seconds()));

The middleware must run after StartSession. When you use the database session driver, Laravel loads the session from the writer even before the middleware runs. Reads from other sessions and on other connections keep their usual routing.

Listening for queries

To see each query your application runs, such as to log slow ones, register a listener with db::listen. Do it in a booted callback in src/app.rs, or in a service provider's boot method:

1use laravel::db;
2use laravel::time::ToSpan;
3 
4.booted(async |_| {
5 db::listen(|query| {
6 if query.elapsed > 500.milliseconds() {
7 let types: Vec<_> = query
8 .bindings
9 .iter()
10 .map(|binding| binding.type_name)
11 .collect();
12 
13 tracing::warn!(
14 connection = %query.connection,
15 sql = %query.sql,
16 bindings = ?types,
17 elapsed = %query.elapsed,
18 location = %query.location,
19 "Slow query",
20 );
21 }
22 });
23})
1use laravel::db;
2use laravel::time::ToSpan;
3 
4.booted(async |_| {
5 db::listen(|query| {
6 if query.elapsed > 500.milliseconds() {
7 let types: Vec<_> = query
8 .bindings
9 .iter()
10 .map(|binding| binding.type_name)
11 .collect();
12 
13 tracing::warn!(
14 connection = %query.connection,
15 sql = %query.sql,
16 bindings = ?types,
17 elapsed = %query.elapsed,
18 location = %query.location,
19 "Slow query",
20 );
21 }
22 });
23})

The listener receives a QueryInfo for every successful query across all connections, including the begins, commits, rollbacks, and savepoints of transactions, exposing connection, sql, elapsed, location, and bindings. Each entry in query.bindings provides the parameter's Rust type_name while leaving value as None by default so passwords and tokens stay out of your logs.

Native SQLx access

When you need something Laravel doesn't wrap, such as a type only one database has, use SQLx directly. Laravel re-exports it as laravel::db::sqlx. db::default_connection_for and db::connection_for return a connection for one driver, whose queries bind values with bind and return SQLx's own rows:

1use laravel::db::{self, sqlx::{Postgres, Row}};
2 
3let connection = db::default_connection_for::<Postgres>()?;
4 
5let rows = connection
6 .query("SELECT name FROM users WHERE tags @> $1")
7 .bind(vec!["beta"])
8 .select()
9 .await?;
10 
11let names = rows.iter().map(|row| row.try_get("name")).collect::<Result<Vec<String>, _>>()?;
1use laravel::db::{self, sqlx::{Postgres, Row}};
2 
3let connection = db::default_connection_for::<Postgres>()?;
4 
5let rows = connection
6 .query("SELECT name FROM users WHERE tags @> $1")
7 .bind(vec!["beta"])
8 .select()
9 .await?;
10 
11let names = rows.iter().map(|row| row.try_get("name")).collect::<Result<Vec<String>, _>>()?;

PostgreSQL numbers its placeholders $1, $2, and so on, while MySQL and SQLite use ?. For SQLx's own query functions, check out a native connection from the pool with acquire. It goes back to the pool when you drop it, so drop it as soon as you're done:

1let mut native = connection.acquire().await?;
2 
3let count: i64 = db::sqlx::query_scalar("SELECT count(*) FROM users")
4 .fetch_one(&mut *native)
5 .await?;
1let mut native = connection.acquire().await?;
2 
3let count: i64 = db::sqlx::query_scalar("SELECT count(*) FROM users")
4 .fetch_one(&mut *native)
5 .await?;

In a transaction that you begin on such a connection, run SQLx queries on tx.native() instead, so they join the transaction.

Queries you run on a native connection skip Laravel's query listeners and sticky reads. After writing through one on a sticky connection, call connection.set_record_modification_state(true).

Testing

Tests that touch the database need tables to query and a clean slate each time. New applications call refresh_database in src/testing.rs so each test starts from your migrations and rolls back when it ends. For a complete overview of database assertions, seeding, and refreshing the database in tests, see testing the database.