Skip to content
Guest
Laravel · Course Syllabus Show lessons
Database & Eloquent · 8 min read · Intermediate

Database Migrations, Factories & Seeders

Version-control your SQL schema with migrations and populate realistic test datasets using Model Factories.

What you'll learn

  • Define foreign keys and composite indexes inside Laravel migrations
  • Generate realistic local test data with `User::factory(20)->create()`
  • Keep `up()` and `down()` reversible for safe rollbacks

Overview

Version-control your SQL schema with migrations and populate realistic test datasets using Model Factories.

Code Example

<?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('lessons', function (Blueprint $table) {
            $table->id();
            $table->foreignId('course_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->unsignedInteger('position')->default(1);
            $table->timestamps();
            $table->index(['course_id', 'position']);
        });
    }
};

Key Takeaways

  • Define foreign keys and composite indexes inside Laravel migrations
  • Generate realistic local test data with User::factory(20)->create()
  • Keep up() and down() reversible for safe rollbacks

Quick Check

Check Your Understanding

Score: 0 / 1

1. What does `$table->foreignId('course_id')->constrained()->cascadeOnDelete()` do?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind