📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework Migrations

Migrations

6 min read Quiz at the end
Create and run database migrations using Laravel's Schema builder to manage table structure.

Migrations

php artisan make:migration create_posts_table

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;

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("is_draft")->default(true);
            $table->timestamp("published_at")->nullable();
            $table->unsignedBigInteger("views")->default(0);
            $table->timestamps();  // created_at, updated_at
            $table->softDeletes(); // deleted_at
        });
    }

    public function down(): void {
        Schema::dropIfExists("posts");
    }
};
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which column type creates an auto-increment primary key?
💡 $table->id() creates an UNSIGNED BIGINT auto-increment primary key.
2. What does cascadeOnDelete() do on a foreign key?
💡 CASCADE automatically deletes child rows when the parent row is deleted.
3. What does softDeletes() add to a migration?
💡 softDeletes() adds a nullable deleted_at timestamp column.
4. What does php artisan migrate:fresh do?
💡 migrate:fresh drops ALL tables and re-runs all migrations.
5. The down() method in a migration should:
💡 down() reverses the migration, enabling rollback.