agyanadda@gmail.com

Laravel Migrations

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 7 of 13

A migration is a PHP file that describes a database table. It works like version control for your database: every developer and server runs the same migrations and gets the same tables.

Set up the database

In .env set DB_CONNECTION, DB_DATABASE, DB_USERNAME and DB_PASSWORD. Create the empty database in MySQL first.

Create a migration

php artisan make:migration create_posts_table creates a file in database/migrations with two methods:

  • up() — create or change the table
  • down() — undo the change

Common column types

  • $table->id() — auto-increment primary key
  • $table->string('title') — VARCHAR
  • $table->text('body') — long text
  • $table->boolean('is_published')->default(false)
  • $table->foreignId('user_id')->constrained() — foreign key to users
  • $table->timestamps() — created_at and updated_at

Commands

  • php artisan migrate — run new migrations
  • php artisan migrate:rollback — undo the last batch
  • php artisan migrate:fresh — drop all tables and run again (deletes all data, development only)

Example

Example — Posts table migration 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->text('body');
            $table->boolean('is_published')->default(false);
            $table->timestamps();
        });
    }

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

Run php artisan migrate and a posts table appears with id, user_id, title, body, is_published, created_at and updated_at columns.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which command runs pending migrations?

Exercise 2 True / False

php artisan migrate:fresh is safe to run on a live production database.

Exercise 3 Fill in the Blank

$table->___() adds created_at and updated_at columns.

Frequently Asked Questions

Not on a shared or live database. Create a new migration that changes the table instead (for example, php artisan make:migration add_slug_to_posts_table). Edit old migrations only on your own machine before anyone else has run them.