Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
Laravel Advanced Free

Migrations

Lesson 6 of 17 · Database 35%

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.

Choose an answer to continue.

Interview Questions

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

Up next

Eloquent Relationships

Lesson 7 of 17 · Database