Database: Schema Builder
- Introduction
- Tables
- Columns
- Indexes
- Foreign keys
- Check constraints
- Vector columns
- Changing large tables
- Inspecting the schema
Introduction
Every database engine uses slightly different DDL syntax for CREATE TABLE and ALTER TABLE, so raw schema SQL written for PostgreSQL may fail against the SQLite database used in local tests. Laravel's schema builder lets you define tables, columns, and indexes once in Rust while generating database-specific SQL for PostgreSQL, MySQL, MariaDB, and SQLite.
Most schema changes live inside migrations. You may call schema() on the migration's transaction to create or alter tables:
1// database/migrations/2026_10_27_143000_create_posts_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("posts", |table| {7 table.id();8 table.foreign_id("user_id").constrained().cascade_on_delete();9 table.string("title");10 table.string("slug").unique();11 table.text("body").nullable();12 table.timestamp("published_at").nullable();13 table.timestamps();1415 table.index(["user_id", "published_at"]);16 })17 .await18}1// database/migrations/2026_10_27_143000_create_posts_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("posts", |table| {7 table.id();8 table.foreign_id("user_id").constrained().cascade_on_delete();9 table.string("title");10 table.string("slug").unique();11 table.text("body").nullable();12 table.timestamp("published_at").nullable();13 table.timestamps();1415 table.index(["user_id", "published_at"]);16 })17 .await18}
Each schema operation runs when you .await it, so call tx.schema() again for each additional statement inside your migration's migrate function:
1tx.schema().drop_if_exists("drafts").await?;2tx.schema().rename("articles", "posts").await?;1tx.schema().drop_if_exists("drafts").await?;2tx.schema().rename("articles", "posts").await?;
To inspect the SQL a schema operation will execute without running it, call to_sql() instead of awaiting it.
Tables
Creating tables
To create a new database table, pass the table name and a closure to create. The closure receives a Blueprint instance that you may use to define the table's columns, indexes, and constraints:
1tx.schema()2 .create("flights", |table| {3 table.id();4 table.string("name");5 table.string("airline");6 table.timestamps();7 })8 .await?;1tx.schema()2 .create("flights", |table| {3 table.id();4 table.string("name");5 table.string("airline");6 table.timestamps();7 })8 .await?;
Changing tables
To modify an existing table, call alter with the table name and a Blueprint closure. Defining columns inside alter adds them to the table, while methods such as rename_column and drop_column modify existing columns:
1tx.schema()2 .alter("users", |table| {3 table.integer("votes").default(0);4 table.rename_column("bio", "about");5 table.drop_column("legacy_flags");6 })7 .await?;1tx.schema()2 .alter("users", |table| {3 table.integer("votes").default(0);4 table.rename_column("bio", "about");5 table.drop_column("legacy_flags");6 })7 .await?;
SQLite cannot perform some alterations in place, such as changing a column type or adding a foreign key. For those operations, Laravel rebuilds the table automatically while preserving its rows and indexes.
Renaming and dropping tables
Use rename to rename an existing table, and drop or drop_if_exists to remove a table and its data:
1tx.schema().rename("posts", "articles").await?;2tx.schema().drop("articles").await?;3tx.schema().drop_if_exists("drafts").await?;1tx.schema().rename("posts", "articles").await?;2tx.schema().drop("articles").await?;3tx.schema().drop_if_exists("drafts").await?;
Calling drop returns an error if the table does not exist, while drop_if_exists succeeds silently. Because renaming a table does not rename its existing indexes or foreign keys (such as posts_user_id_foreign), reference them by their original names if you drop them in a later migration.
Table options
You may configure these table options inside create. MySQL and MariaDB honor all of them, while other databases ignore options they do not support:
| Method | Effect |
|---|---|
table.temporary() |
Creates a temporary table, which only this database session sees |
table.engine("InnoDB") |
Sets the MySQL and MariaDB storage engine |
table.charset("utf8mb4") |
Sets the MySQL and MariaDB default character set |
table.collation("utf8mb4_unicode_ci") |
Sets the MySQL and MariaDB default collation |
table.comment("Blog posts") |
Adds a comment on PostgreSQL, MySQL, and MariaDB. It works in alter too |
Columns
Column types
The schema builder provides methods for adding every common column type to your table blueprint. Unless noted with (), each method accepts the column's name:
| Method | Column |
|---|---|
id() |
An auto-incrementing big integer primary key named id |
increments, big_increments, medium_increments, small_increments, tiny_increments |
An auto-incrementing integer primary key of that size |
integer, big_integer, medium_integer, small_integer, tiny_integer |
An integer of that size |
float, double |
A floating-point number |
decimal(name, |
An exact decimal with total digits, places of them after the decimal point |
boolean |
A boolean |
char, string |
Text of up to 255 characters. Set another length with .length(n) |
tiny_text, text, medium_text, long_text |
Longer text. Only MySQL and MariaDB distinguish the sizes |
enumeration(name, |
Text restricted to the listed allowed values |
set(name, |
A MySQL and MariaDB set |
json, jsonb |
A JSON document. Only PostgreSQL distinguishes jsonb |
date, time, time_tz |
A calendar date or a time of day. Only PostgreSQL stores the time zone of time_tz |
date_time |
A wall-clock date and time without a time zone, such as an appointment at 9:00 wherever it takes place |
timestamp |
A moment in time, which Laravel writes in UTC: timestamp on PostgreSQL, and datetime on MySQL, MariaDB, and SQLite |
timestamps() |
Nullable created_at and updated_at timestamps |
soft_deletes() |
A nullable deleted_at timestamp |
year |
A year |
binary |
Binary data |
uuid, ulid |
A UUID or ULID |
foreign_id, foreign_uuid, foreign_ulid |
A key of another table, ready for a foreign key |
ip_address, mac_address |
A network address, stored as text |
geometry, geography |
A spatial value. PostgreSQL needs the PostGIS extension |
vector(name, |
A fixed-length embedding for vector columns |
morphs, uuid_morphs, ulid_morphs, and their nullable_ forms |
{name}_type and {name}_id columns with an index on both |
remember_token() |
A nullable remember_token of 100 characters |
Each column decodes into the same Rust type across every supported database, whether you map it onto a model or a db::FromRow struct:
| Columns | Rust type |
|---|---|
id, foreign_id, and the integers |
i64, or a smaller integer such as i32 |
float, double |
f64 |
decimal |
laravel::numeric::Decimal |
boolean |
bool |
char, string, the text types, enumeration, set, and mac_address |
String |
json, jsonb |
serde_json::Value, or your own type in db::Json<T> |
date |
laravel::time::civil::Date |
time, time_tz |
laravel::time::civil::Time |
timestamps(), soft_deletes(), and the other date and time types |
laravel::time::Timestamp, or civil::DateTime for a wall-clock time |
year |
i32 |
binary |
Vec<u8> |
uuid, foreign_uuid |
laravel::str::Uuid |
ulid, foreign_ulid |
laravel::str::Ulid |
ip_address |
std::net::IpAddr |
vector |
laravel::db::Vector |
When a column is marked .nullable(), wrap its corresponding Rust field type in Option<T>.
Column modifiers
Columns are NOT NULL by default. Chain column modifiers to customize a column's definition:
1tx.schema()2 .alter("users", |table| {3 table.string("nickname").length(50).nullable().comment("Shown next to posts");4 })5 .await?;1tx.schema()2 .alter("users", |table| {3 table.string("nickname").length(50).nullable().comment("Shown next to posts");4 })5 .await?;
| Modifier | Effect |
|---|---|
.nullable() |
Allows NULL |
.default(value) |
Sets a column's default value when omitted on insert |
.use_current() |
Defaults a date or time column to the current time |
.use_current_on_update() |
On MySQL and MariaDB, sets a timestamp to the current time whenever its row changes |
.stored_as(expr), .virtual_as(expr) |
Defines a generated column |
.unsigned() |
Makes an integer unsigned on MySQL and MariaDB |
.auto_increment() |
Makes an integer auto-incrementing, which also makes it the primary key |
.starting_value(1000) |
Sets the first value of an auto-incrementing column on PostgreSQL, MySQL, and MariaDB |
.length(n) |
Sets the length of a string, char, or binary column |
.precision(n) |
Sets the fractional digits of seconds for a time column (overriding the connection's time precision), or sets the bits of a float |
.comment(text) |
Adds a comment on PostgreSQL, MySQL, and MariaDB |
.charset(name), .collation(name) |
Sets a text column's character set on MySQL and MariaDB, or its collation |
.after(column), .first() |
Places a new column on MySQL and MariaDB |
.invisible() |
Leaves the column out of select * on MySQL and MariaDB |
.instant(), .lock(Lock::None) |
On MySQL and MariaDB, alters large tables without copying rows or blocking writes |
.primary(), .unique(), .index(), .full_text(), .spatial_index() |
Adds an index on the column |
To place several new columns after a given column on MySQL and MariaDB, add them inside table.after(column, |table| { .. }), where each column is placed immediately after the previous column:
1table.after("password", |table| {2 table.string("address_line1");3 table.string("address_line2").nullable();4 table.string("city");5});1table.after("password", |table| {2 table.string("address_line1");3 table.string("address_line2").nullable();4 table.string("city");5});
Defaults
Default values populate a column when an insert omits it. .default accepts either a literal value or a raw expression. Literal values such as 0, false, or "draft" are escaped for the active database, while db::raw! expressions are emitted verbatim:
1use laravel::db;23tx.schema()4 .create("flights", |table| {5 table.id();6 table.string("status").default("scheduled");7 table.integer("seats").default(180);8 table.boolean("international").default(false);9 table.json("movies").default("[]");10 table.date("booked_on").default(db::raw!("current_date"));11 })12 .await?;1use laravel::db;23tx.schema()4 .create("flights", |table| {5 table.id();6 table.string("status").default("scheduled");7 table.integer("seats").default(180);8 table.boolean("international").default(false);9 table.json("movies").default("[]");10 table.date("booked_on").default(db::raw!("current_date"));11 })12 .await?;
A model reads a column's database default when you mark its field #[default].
Generated columns
Generated columns derive their values automatically from other columns in the same row. Pass an expression built with col to stored_as or virtual_as:
1use laravel::db::col;23tx.schema()4 .create("line_items", |table| {5 table.id();6 table.integer("price");7 table.integer("quantity");8 table.integer("total").stored_as(col("price") * col("quantity"));9 })10 .await?;1use laravel::db::col;23tx.schema()4 .create("line_items", |table| {5 table.id();6 table.integer("price");7 table.integer("quantity");8 table.integer("total").stored_as(col("price") * col("quantity"));9 })10 .await?;
stored_as computes and persists the value whenever a row is inserted or updated. virtual_as computes the value on read and requires PostgreSQL 18 or later when used on PostgreSQL.
Changing columns
To modify an existing column's type or attributes, redefine it inside alter and chain .change():
1tx.schema()2 .alter("users", |table| {3 table.string("name").length(100).nullable().change();4 })5 .await?;1tx.schema()2 .alter("users", |table| {3 table.string("name").length(100).nullable().change();4 })5 .await?;
Because .change() replaces the column's full definition, include every modifier the column should retain. Any modifier you omit is removed; for example, omitting .nullable() changes a nullable column back to NOT NULL.
When changing a column's type on PostgreSQL requires an explicit cast, chain .using(...) to convert existing values:
1use laravel::db;23table.date("birthday").change().using(db::raw!("birthday::date"));1use laravel::db;23table.date("birthday").change().using(db::raw!("birthday::date"));
Renaming and dropping columns
Use rename_column and drop_column inside alter to rename or remove existing columns on a table:
1tx.schema()2 .alter("users", |table| {3 table.rename_column("bio", "about");4 table.drop_column(["legacy_flags", "legacy_notes"]);5 })6 .await?;1tx.schema()2 .alter("users", |table| {3 table.rename_column("bio", "about");4 table.drop_column(["legacy_flags", "legacy_notes"]);5 })6 .await?;
drop_column accepts either a single column name or a list of names. When you drop a column from a composite index, MySQL and MariaDB can keep the index on the remaining columns. Drop the index first if you want to remove it on every database.
You may also use drop_timestamps, drop_soft_deletes, drop_remember_token, and drop_morphs to remove the columns created by their corresponding helper methods.
Indexes
Creating indexes
Indexes let the database locate matching rows without scanning the entire table, and unique indexes also prevent duplicate values. You may attach an index to a single column with a column modifier, or define composite indexes across multiple columns on the blueprint:
1tx.schema()2 .create("users", |table| {3 table.id();4 table.string("email").unique();5 table.foreign_id("team_id");6 table.timestamps();78 table.index(["team_id", "created_at"]);9 })10 .await?;1tx.schema()2 .create("users", |table| {3 table.id();4 table.string("email").unique();5 table.foreign_id("team_id");6 table.timestamps();78 table.index(["team_id", "created_at"]);9 })10 .await?;
| Method | Index |
|---|---|
primary(columns) |
The primary key |
unique(columns) |
A unique index |
index(columns) |
An index |
full_text(columns) |
A full-text index for db::search, on PostgreSQL, MySQL, and MariaDB |
spatial_index(columns) |
A spatial index, except on SQLite |
vector_index(column) |
Cosine-distance index for vector columns |
Laravel generates index names using the convention {table}_{columns}_{kind}, such as users_email_unique or users_team_id_created_at_index. You can specify a custom name with .name(..):
1table.unique(["team_id", "email"]).name("users_team_email_unique");1table.unique(["team_id", "email"]).name("users_team_email_unique");
To choose a specific index algorithm, such as gin for a PostgreSQL jsonb column, chain .algorithm(..):
1table.index("attributes").algorithm("gin");1table.index("attributes").algorithm("gin");
On PostgreSQL, full-text indexes use the english text search configuration by default. To use a different configuration, chain .language("simple") on the index and pass the same language to db::search so queries can use the index.
Renaming and dropping indexes
To drop an index, pass either its explicit name or the list of indexed columns so Laravel can derive its conventional name:
1tx.schema()2 .alter("users", |table| {3 table.drop_unique(["email"]);4 table.drop_index("users_team_id_created_at_index");5 table.rename_index("users_name_index", "users_display_name_index");6 })7 .await?;1tx.schema()2 .alter("users", |table| {3 table.drop_unique(["email"]);4 table.drop_index("users_team_id_created_at_index");5 table.rename_index("users_name_index", "users_display_name_index");6 })7 .await?;
Alongside drop_index and drop_unique, the blueprint provides drop_full_text, drop_spatial_index, drop_vector_index, and drop_primary() (which takes no arguments since a table has only one primary key).
Foreign keys
Foreign key constraints enforce referential integrity across tables. Calling constrained infers the referenced table from the column name, so user_id automatically references id on users:
1tx.schema()2 .create("posts", |table| {3 table.id();4 table.foreign_id("user_id").constrained().cascade_on_delete();5 })6 .await?;1tx.schema()2 .create("posts", |table| {3 table.id();4 table.foreign_id("user_id").constrained().cascade_on_delete();5 })6 .await?;
Use references to target an explicit table, .column(..) to reference a column other than id, or foreign for composite keys. Chain column modifiers such as .nullable() before constrained or references, since those methods transition the builder to the foreign key constraint:
1table.foreign_id("author_id").nullable().references("users").null_on_delete();2table.foreign_uuid("team_uuid").references("teams").column("uuid");3table.foreign(["order_number"]).references("orders", ["number"]).cascade_on_update();1table.foreign_id("author_id").nullable().references("users").null_on_delete();2table.foreign_uuid("team_uuid").references("teams").column("uuid");3table.foreign(["order_number"]).references("orders", ["number"]).cascade_on_update();
Configure delete and update actions with these methods:
| Method | Effect |
|---|---|
cascade_on_delete(), cascade_on_update() |
Deletes the row, or changes its key |
restrict_on_delete(), restrict_on_update() |
Refuses the change |
null_on_delete(), null_on_update() |
Sets the key to NULL |
no_action_on_delete(), no_action_on_update() |
Refuses the change, checked at the end of the statement |
Laravel generates foreign key names using the convention {table}_{columns}_foreign (such as posts_user_id_foreign), or you can specify a custom name with .name(..). You may drop a foreign key by name or by its columns, or call drop_constrained_foreign_id to drop both the constraint and its column in one step:
1table.drop_foreign("posts_user_id_foreign");2table.drop_foreign(["user_id"]);3table.drop_constrained_foreign_id("author_id");1table.drop_foreign("posts_user_id_foreign");2table.drop_foreign(["user_id"]);3table.drop_constrained_foreign_id("author_id");
Turning foreign key checks off
When truncating or seeding related tables, foreign key constraints can force an awkward execution order. without_foreign_key_constraints runs your callback inside a transaction with foreign key checks disabled and restores them automatically when the transaction finishes, even if the callback returns an error. Call it on a connection's schema, such as in a seeder or console command:
1use laravel::db;23db::default_connection()?4 .schema()5 .without_foreign_key_constraints(async |_| {6 db::table("posts").truncate().await?;7 db::table("users").truncate().await8 })9 .await?;1use laravel::db;23db::default_connection()?4 .schema()5 .without_foreign_key_constraints(async |_| {6 db::table("posts").truncate().await?;7 db::table("users").truncate().await8 })9 .await?;
On PostgreSQL and SQLite, all foreign key references must be valid again before the transaction commits. SQLite verifies every reference at commit time, while PostgreSQL only defers checks for foreign keys created with .deferrable().
Check constraints
Check constraints enforce a condition on every row written to a table, such as ensuring a product's price is never negative. The database rejects any insert or update that violates the constraint. Build the expression using the query builder condition API:
1use laravel::db::col;23tx.schema()4 .create("products", |table| {5 table.id();6 table.decimal("price", 8, 2);7 table.check("products_price_check", col("price").ge(0));8 })9 .await?;1use laravel::db::col;23tx.schema()4 .create("products", |table| {5 table.id();6 table.decimal("price", 8, 2);7 table.check("products_price_check", col("price").ge(0));8 })9 .await?;
To remove an existing check constraint, call table.drop_check("products_price_check").
Vector columns
Vector columns store fixed-length embeddings for vector similarity queries. They are supported on PostgreSQL (with the pgvector extension) and MariaDB 11.7 or later. On PostgreSQL, install pgvector on the server, then call ensure_vector_extension to enable it for your database. MariaDB has built-in vector support, so skip that call:
1use laravel::db::Driver;23if tx.driver() == Driver::Postgres {4 tx.schema().ensure_vector_extension().await?;5}67tx.schema()8 .create("documents", |table| {9 table.id();10 table.string("title");11 table.vector("embedding", 3).index();12 })13 .await?;1use laravel::db::Driver;23if tx.driver() == Driver::Postgres {4 tx.schema().ensure_vector_extension().await?;5}67tx.schema()8 .create("documents", |table| {9 table.id();10 table.string("title");11 table.vector("embedding", 3).index();12 })13 .await?;
Use the number of dimensions your embedding model returns. This example uses the three-dimensional embedding from the vector similarity example.
Chaining .index() directly on a vector column automatically creates a cosine-distance vector index (HNSW with vector_cosine_ops on PostgreSQL, or VECTOR INDEX ... DISTANCE=cosine on MariaDB). When adding a vector index to an existing column inside alter, call table.vector_index("embedding") instead of table.index("embedding"). MariaDB supports indexing at most one vector column per table, and the column must be NOT NULL.
Changing large tables
A change that completes instantly on a new table can block a busy production table for minutes if the database rewrites rows or locks writes. Each database engine provides specific options to keep tables available during alterations.
On PostgreSQL, creating an index normally blocks writes to the table until the index finishes building. Chain .online() to emit CREATE INDEX CONCURRENTLY so writes can continue. Because PostgreSQL does not allow concurrent index creation inside a transaction, place it in a non-transactional migration that accepts &AnyConnection. Other databases ignore .online():
1use laravel::db::AnyConnection;23pub async fn migrate(db: &AnyConnection) -> laravel::Result<()> {4 db.schema()5 .alter("users", |table| {6 table.index("last_seen_at").online();7 })8 .await9}1use laravel::db::AnyConnection;23pub async fn migrate(db: &AnyConnection) -> laravel::Result<()> {4 db.schema()5 .alter("users", |table| {6 table.index("last_seen_at").online();7 })8 .await9}
On MySQL and MariaDB, chaining .instant() adds, modifies, or drops a column by updating only table metadata without copying rows. Chaining .lock(..) on a column, index, or foreign key caps the locking level allowed for the statement: Lock::None permits concurrent reads and writes, while Lock::Shared permits concurrent reads. If the database cannot perform the operation under those constraints, the statement fails instead of copying or locking the table. Other databases ignore both options:
1use laravel::db::schema::Lock;23tx.schema()4 .alter("orders", |table| {5 table.string("coupon").nullable().instant();6 table.index("coupon").lock(Lock::None);7 })8 .await?;1use laravel::db::schema::Lock;23tx.schema()4 .alter("orders", |table| {5 table.string("coupon").nullable().instant();6 table.index("coupon").lock(Lock::None);7 })8 .await?;
Inspecting the schema
You may inspect your database's existing tables, columns, and indexes from migrations or console commands:
1if !tx.schema().has_table("flights").await? {2 // ...3}45if tx.schema().has_column("users", "email").await? {6 // ...7}1if !tx.schema().has_table("flights").await? {2 // ...3}45if tx.schema().has_column("users", "email").await? {6 // ...7}
| Method | Returns |
|---|---|
has_table(table) |
Whether the table exists |
has_column(table,, has_columns(table, |
Whether the table has the given column, or all of the given columns |
has_index(table,, has_unique(table, |
Whether the table has an index or unique index with that name or on those columns |
has_view(view) |
Whether the view exists |
tables(), views(), types() |
The database's tables, views, and PostgreSQL types |
columns(table), indexes(table), foreign_keys(table) |
The table's columns, indexes, and foreign keys |
Column type names and default expressions are returned in each database engine's native format, so they vary across PostgreSQL, MySQL, MariaDB, and SQLite.