Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Laravel Migrations
Laravel Advanced FREE

Migrations

Lesson 2 of 17 Advanced Interactive

Migrations are version control for your database schema.

Commands

  • php artisan make:migration create_posts_table
  • php artisan migrate
  • php artisan migrate:rollback

Syntax

LARAVEL
Schema::create("posts", function (Blueprint $table) {
    $table->id();
    $table->foreignId("user_id")->constrained();
    $table->string("title");
    $table->text("body");
    $table->boolean("published")->default(false);
    $table->timestamps();
});
Database 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");
    }
};
?>

Practice

1
Exercise

Create a migration for a comments table.

Answer
Schema::create("comments", function ($table) {
    $table->id();
    $table->foreignId("user_id")->constrained();
    $table->foreignId("post_id")->constrained();
    $table->text("body");
    $table->timestamps();
});

Quick Quiz

1

What does migrate:rollback do?

Rollback reverses the last batch of migrations.

Interview Questions

They track schema changes in version control, can be rolled back, work across environments.