Migrations and the Schema Builder
Part 2 · Laravel Rust. Learn what a database is, then create the Rusty Bean Café's menu and order tables with Laravel Rust migrations and the schema builder.
Until now, the Rusty Bean Café website has forgotten everything the moment it stopped running. Orders, menu items, customers: all gone on restart. A real café needs a memory that lasts. In this lesson you’ll meet the database, learn how its tables are shaped, and use Laravel Rust migrations to build the café’s first tables, all from Rust code.
What is a database?
A database is a program whose whole job is to store data safely and find it again quickly. Think of it as a very organised filing cabinet that never loses a page, even if the power goes out.
Most web apps use a relational database, such as PostgreSQL, MySQL, MariaDB or SQLite. “Relational” means the data lives in tables that can point at each other.
Tables, rows and columns
A table looks a lot like a spreadsheet. Here is the café’s menu as a table:
menu_items+----+------------+-------------+-----------+| id | name | price_cents | available |+----+------------+-------------+-----------+| 1 | Espresso | 300 | true || 2 | Flat White | 400 | true || 3 | Croissant | 325 | false |+----+------------+-------------+-----------+- A column is one kind of information, like
nameorprice_cents. Every column has a type: text, whole number, true/false, and so on. - A row is one record: one menu item. Each row fills in every column.
- The primary key is a column whose value is unique for every row, so you can point at exactly one row. Here it’s
id. Two lattes may have the same name, but never the sameid.
Prices are stored as whole cents (325 means $3.25), just like in our Rust lessons, because decimals like 3.25 can drift with rounding.
Foreign keys: tables pointing at tables
An order contains several items. Instead of copying the full menu item into every order, the order_items table stores the id of the menu item it refers to:
order_items+----+----------+--------------+----------+| id | order_id | menu_item_id | quantity |+----+----------+--------------+----------+| 1 | 7 | 2 | 2 |+----+----------+--------------+----------+menu_item_id is a foreign key: a column holding another table’s primary key. It’s like writing “see page 2” instead of copying page 2. The database can even refuse a foreign key that points at nothing, which keeps your data honest.
SQL: the language databases speak
You talk to a relational database with SQL (Structured Query Language). A command to build a table looks like this:
CREATE TABLE menu_items ( id BIGSERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, price_cents INTEGER NOT NULL);The catch: every database engine speaks a slightly different dialect. That SQL is for PostgreSQL; SQLite and MySQL want small differences. Laravel Rust’s schema builder lets you describe tables once, in Rust, and it writes the right SQL for whichever engine you use.
What is a migration?
Imagine you add a note column to the orders table on your laptop. Your teammate pulls your code, runs the app, and it crashes, because their database has no note column. Somebody has to remember to change every database by hand.
A migration solves this. It’s a small, dated file that describes one change to the database, such as “create the orders table” or “add a note column”. The official docs call migrations version control for your database: the changes live in your code, so everyone’s database can be brought up to date with one command.
In Laravel Rust, migrations have some special features:
- Each migration is a Rust file in the
database/migrations/folder. - Laravel records every migration it has run in a
migrationstable, so each one runs only once per database. - Migrations are compiled into your app’s binary. A deployed server can run them without having your source files around.
Note
Laravel Rust is brand new (beta, December 2026), and this module follows the official documentation. Keep the Migrations guide (opens in new tab) and Schema Builder guide (opens in new tab) open in a tab while you work.
Creating your first migration
Generate a migration with the Laravel CLI:
laravel make:migration create_menu_items_tableThis writes a new file in database/migrations/ whose name starts with the current UTC time, such as 2026_12_03_090000_create_menu_items_table.rs. Because names start with the time, migrations run in the order you created them. The command also reads the name: create_menu_items_table tells it to scaffold a new menu_items table with an id and timestamps already in place.
Fill it in like this:
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("menu_items", |table| { table.id(); table.string("name").unique(); table.text("description").nullable(); table.integer("price_cents"); table.boolean("available").default(true); table.timestamps(); }) .await}Line by line:
use laravel::db::AnyTransaction;brings in the type for a database transaction, a group of changes that either all succeed or all get undone. The'_inAnyTransaction<'_>is a lifetime that the compiler works out for you, so it’s safe to ignore for now (lifetimes come from Borrowing and References).- Every migration has exactly one public
async fn migrate. Laravel calls it once per database. It returnslaravel::Result<()>, so errors flow out with?, just like in error handling with ?. tx.schema()opens the schema builder, and.create("menu_items", |table| { ... })says “create a table calledmenu_items”. The closure receives a blueprint,table, that you describe columns on.table.id()adds an auto-incrementing big-integer primary key namedid. The database picks 1, 2, 3… for you.table.string("name").unique()adds a text column (up to 255 characters) and a unique index, so two items can’t share a name.table.text("description").nullable()adds a longer text column. Columns are NOT NULL by default, meaning they must have a value;.nullable()allows them to be empty (NULL).table.integer("price_cents")stores the price in whole cents.table.boolean("available").default(true)means a new item is available unless you say otherwise.table.timestamps()addscreated_atandupdated_atcolumns that Laravel fills in for you..awaitactually runs it. Nothing touches the database until you await.
Because migrate takes &mut AnyTransaction, Laravel wraps the whole migration in a transaction. On PostgreSQL and SQLite, a failed migration rolls back cleanly, so you can fix the file and try again.
Warning
MySQL and MariaDB commit table changes immediately, even inside a transaction. If a migration fails halfway on those engines, earlier statements stay applied. The docs recommend keeping each table change in its own migration file.
Tables that point at each other
Next, orders and their line items. Create two more migrations (laravel make:migration create_orders_table, then create_order_items_table):
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("orders", |table| { table.id(); table.foreign_id("user_id").constrained().cascade_on_delete(); table.string("customer_name"); table.string("status").default("pending"); table.integer("total_cents").default(0); table.text("note").nullable(); table.timestamps(); }) .await}The new piece is table.foreign_id("user_id").constrained().cascade_on_delete():
foreign_id("user_id")adds a column that will hold another table’s key..constrained()turns it into a real foreign key. Laravel guesses the target from the name:user_idpoints atidon theuserstable, which every new app already has..cascade_on_delete()says “if that user is deleted, delete their orders too”.
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("order_items", |table| { table.id(); table.foreign_id("order_id").constrained().cascade_on_delete(); table.foreign_id("menu_item_id").constrained().restrict_on_delete(); table.integer("quantity"); table.integer("unit_price_cents"); table.timestamps();
table.index(["order_id", "menu_item_id"]); }) .await}Two new ideas here:
.restrict_on_delete()makes the database refuse to delete a menu item that still appears in an order. Old receipts should never point at nothing.table.index([...])adds an index: like the index at the back of a book, it lets the database find rows by those columns without reading the whole table.
We copy unit_price_cents into each line item on purpose: if the café raises the price of a flat white next month, last week’s receipts must still show what the customer actually paid.
Running your migrations
New apps register the migrations folder in src/app.rs for you, using laravel::db::migrations!("database/migrations"). That macro reads the folder at compile time and bakes every .rs file into your binary. Now run:
laravel migratemigrate creates the migrations table the first time, then runs every pending migration in name order. To see what has run, use:
laravel migrate:statusMigration Batch Status2026_12_03_090000_create_menu_items_table 1 ran2026_12_03_091000_create_orders_table 1 ran2026_12_03_092000_create_order_items_table 1 ranThe batch number groups the migrations that ran together. While you’re experimenting locally, laravel migrate:fresh drops every table and runs all migrations from scratch.
Tip
Want to try this without installing a database server? The database guide (opens in new tab) shows how to switch to SQLite, which keeps everything in a single file: enable the database-sqlite Cargo feature and set DB_CONNECTION=sqlite and DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwc in .env.
Migrations only move forward
Laravel Rust migrations have no “down” function and no rollback command. Undoing a change in production could destroy live data, so instead you write a new migration that changes things again, using alter:
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .alter("menu_items", |table| { table.string("size").length(20).nullable(); }) .await}Defining a column inside alter adds it to the existing table. Methods like drop_column and rename_column work there too.
Important
Laravel tracks each migration by its file name. Once a migration has run on a shared or production database, never edit or rename it: an edited file won’t run again, and a renamed one will run a second time. Write a new migration instead.
Framework tables in one line
Some Laravel features keep their data in tables you rarely touch. Queued jobs (coming in Queued Jobs) need tables like jobs and failed_jobs. Instead of copying their schema, you write a migration that holds a single macro:
laravel::queue::tables!();That macro defines the whole migrate function for you and creates the jobs, failed_jobs, job_batches and job_batch_jobs tables. There are siblings too: laravel::cache::tables!(), laravel::session::table!(), laravel::feature::table!() and laravel::workflow::tables!().
Try it yourself
- The café wants to track loyalty stamps. Write a migration that creates a
loyalty_cardstable with anid, auser_idforeign key that deletes cards when the user is deleted, astampsinteger that defaults to0, and timestamps. - Write a second migration that adds a nullable
allergenstext column tomenu_items.
Show solution
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .create("loyalty_cards", |table| { table.id(); table.foreign_id("user_id").constrained().cascade_on_delete(); table.integer("stamps").default(0); table.timestamps(); }) .await}use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { tx.schema() .alter("menu_items", |table| { table.text("allergens").nullable(); }) .await}Then run laravel migrate. Notice we added the column with a new migration instead of editing the old one.
Recap
- A database stores data in tables of rows and columns; a primary key identifies one row, and a foreign key points at a row in another table.
- A migration is a dated Rust file in
database/migrations/that changes the schema; Laravel records each one so it runs once. - Migrations compile into your binary, so servers can run
migratewithout your source code. - The schema builder (
tx.schema().create(...)/.alter(...)) writes the right SQL for PostgreSQL, MySQL, MariaDB or SQLite. - Migrations only move forward: change things with a new migration, and never edit one that has already run in production.
- Framework tables come from one-line macros like
laravel::queue::tables!().
What’s next
The tables exist, but our Rust code can’t use them yet. Next, in Models and Relationships, you’ll turn each table into a typed Rust struct.
0 of 35 lessons complete