Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 67 ยท Databases and Migrations

Migrations

Learn Laravel migrations: create tables with Schema and Blueprint, choose column types, add indexes and foreign keys, alter tables, and run migrate, rollback and fresh.

A database schema changes over time: a new column here, an index there. If you edit the database by hand, your teammates and your production server drift out of sync with your laptop. Migrations fix that. Each migration is a small PHP file describing one change, stored in Git next to your code, and run in order by php artisan migrate. Everyone ends up with the same schema, and every change can be reviewed like any other code.

This lesson shows how to generate and write migrations, the column types and modifiers you will use daily, how indexes and foreign keys are declared, how to change an existing table, and how the migrate family of commands tracks what has run. For the SQL these migrations produce, see creating tables in the SQL tutorial; for the builder you use afterwards, see the query builder.

Generating a migration

Terminal
php artisan make:migration create_posts_table

The generator creates a timestamped file in database/migrations, such as 2026_03_01_120000_create_posts_table.php. The timestamp decides the order. Because the name starts with create_ and ends with _table, Laravel pre-fills the file for a new table. For a change to an existing table, name it descriptively, and use --table:

Terminal
php artisan make:migration add_slug_to_posts_table --table=posts

A migration is an anonymous class with two methods:

PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('body');
            $table->boolean('published')->default(false);
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

up() applies the change; down() undoes it, which makes migrate:rollback possible. The Blueprint object collects column definitions, and Laravel compiles them into the right CREATE TABLE statement for your database. The same file works on SQLite, MySQL and PostgreSQL.

Column types and modifiers

Each Blueprint method adds a column of a given type. These are the ones you will use most:

Method Column
id() Auto-incrementing big integer primary key named id
string('name', 100) VARCHAR, length 255 by default
text('body') Long text
integer, bigInteger, unsignedInteger Whole numbers
decimal('price', 8, 2) Exact decimal: 8 digits, 2 after the point
boolean('active') True or false
date, dateTime, timestamp Dates and times
json('options') JSON document
uuid('uuid'), ulid('ulid') Unique identifier strings
foreignId('user_id') Unsigned big integer meant for a foreign key
timestamps() Nullable created_at and updated_at
softDeletes() Nullable deleted_at (see soft deletes)

Money belongs in decimal (or an integer count of cents), never float, because floating-point numbers cannot represent most decimals exactly.

Modifiers chain after the type:

PHP
$table->string('nickname')->nullable();
$table->integer('stock')->default(0);
$table->string('email')->unique();
$table->string('phone')->nullable()->after('email'); // MySQL only
$table->timestamp('created_at')->useCurrent();
$table->text('notes')->comment('Internal only');

Columns are NOT NULL unless you say nullable(). Choose that deliberately: a nullable column forces every reader of the data to handle a missing value.

Indexes and foreign keys

An index makes lookups on a column fast, at the cost of slower writes and extra space. Add one for columns you filter, sort or join on:

PHP
$table->index('published_at');
$table->index(['user_id', 'published_at']);   // composite: order matters
$table->unique('slug');
$table->unique(['team_id', 'email']);          // unique per team
$table->fullText('body');                      // where the database supports it

A foreign key makes the database itself reject orphan rows. The short form is:

PHP
$table->foreignId('user_id')->constrained()->cascadeOnDelete();

constrained() guesses the table from the column name (user_id becomes users). cascadeOnDelete() deletes the posts when their user is deleted; alternatives are restrictOnDelete(), nullOnDelete() and cascadeOnUpdate(). The long form spells everything out:

PHP
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')->references('id')->on('users')->onDelete('cascade');

Create parent tables first: a foreign key to a table that does not exist yet fails, which is why migration order (the timestamp) matters. Relationships built on these keys are the subject of Eloquent relationships.

erDiagram
    users ||--o{ posts : "user_id"
    posts ||--o{ comments : "post_id"
    users {
        bigint id PK
        string email UK
    }
    posts {
        bigint id PK
        bigint user_id FK
        string slug UK
    }
    comments {
        bigint id PK
        bigint post_id FK
    }

Foreign keys point from the child table to the parent's primary key.

Under the hood, Schema::create turns a list of column objects into SQL. This stand-in does the same on SQLite so you can see exactly what a Blueprint produces.

PHP A tiny Blueprint that compiles to SQL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real Blueprint has hundreds of lines of grammar code per database, but the flow is this one: your closure fills a blueprint, the schema compiles it to statements, the connection runs them.

Changing existing tables

Never edit a migration that has already run on a shared database. Add a new one. Inside it use Schema::table:

PHP
public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string('subtitle')->nullable();          // add
        $table->renameColumn('body', 'content');         // rename
        $table->string('title', 200)->change();          // modify
        $table->dropColumn('legacy_flag');               // remove
        $table->dropIndex(['published_at']);             // remove an index
        $table->dropForeign(['user_id']);                // remove a foreign key
    });
}

When you call ->change(), restate the column's complete definition, including modifiers such as nullable() and default(): anything you leave out is dropped. Other helpers are Schema::rename('old', 'new'), Schema::drop(), Schema::dropIfExists(), Schema::hasTable('posts') and Schema::hasColumn('posts', 'slug'). Write the down() method as the exact opposite of up(). If undoing is impossible (dropping a column loses its data), say so by throwing an exception rather than pretending.

Running migrations

Terminal
php artisan migrate                 # run every pending migration
php artisan migrate:status          # list each migration as Ran or Pending
php artisan migrate --pretend       # print the SQL, change nothing
php artisan migrate:rollback        # undo the last batch
php artisan migrate:rollback --step=2   # undo the last two migrations
php artisan migrate:fresh           # drop ALL tables, then migrate
php artisan migrate:fresh --seed    # ...and run the seeders
php artisan migrate --force         # required to run in production

Laravel records progress in a migrations table: one row per migration file with a batch number. Everything run by a single migrate command shares a batch, and rollback undoes the highest batch by calling each file's down() in reverse order. migrate:fresh ignores down() entirely and drops every table, so it is for local development only: on a production database it would destroy your data. Seeding after a fresh migration is the topic of seeders and factories.

flowchart LR
    F["migration files<br/>database/migrations"] --> M["php artisan migrate"]
    M --> T["migrations table<br/>name + batch"]
    M --> D[("database schema")]
    R["migrate:rollback"] -->|"down() of last batch"| D

The migrations table remembers which files ran; rollback replays the last batch backwards.

The second stand-in is a mini migrator with a migrations table, batch numbers, migrate and rollback.

PHP A mini migrator with batches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What decides the order in which migrations run?

    make:migration prefixes the file name with a timestamp, and migrate runs the pending files in that order. That is why parent tables must have earlier timestamps than the tables with foreign keys to them.
  2. 2. You shipped a migration last month and now need a new subtitle column on posts. What should you do?

    Migrations that already ran elsewhere are history. A new migration carries the change to every environment, and migrate:fresh would delete production data.
  3. 3. What does $table->foreignId('user_id')->constrained()->cascadeOnDelete() do?

    constrained() infers the users table from the column name and adds the foreign key. cascadeOnDelete() chooses the ON DELETE CASCADE behavior.
  4. 4. Which command undoes only the most recent batch of migrations?

    rollback calls down() for every migration in the last batch, newest first. fresh drops all tables, status only lists, pretend only prints SQL.
  5. 5. Why should money be stored in decimal (or integer cents) rather than float?

    Binary floating point turns values like 0.1 into approximations, so sums drift. Decimal and integer columns are exact.

Summary

  • Migrations are timestamped PHP files with up() and down(), kept in Git and run in order, so every environment gets the same schema.
  • Generate them with php artisan make:migration, create tables with Schema::create and a Blueprint, and modify them with Schema::table.
  • Pick column types deliberately (decimal for money), remember columns are NOT NULL unless nullable(), and add index/unique for the columns you query.
  • foreignId()->constrained()->cascadeOnDelete() declares a foreign key; parent tables must be created first.
  • Never edit a migration that has run elsewhere; add a new one. With change(), restate the whole column definition.
  • migrate, migrate:status, migrate:rollback, migrate:fresh and --pretend manage the schema; the migrations table tracks batches, and fresh is for development only.

Next: Seeders and Factories