Laravel

Lesson 06

Migrations and schema constraints

Use migrations to encode database rules such as foreign keys, required fields, uniqueness, and timestamps.

Good Code

database/migrations/create_reviews_table.php
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('reviews', function (Blueprint $table) {
    // Constraints protect core review data even when writes come from jobs or imports.
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('slug');
    $table->string('status')->default('draft');
    $table->text('body');
    $table->timestamps();

    $table->unique(['user_id', 'slug']);
});

Bad Code

database/migrations/create_reviews_table.php
<?php

Schema::create('reviews', function (Blueprint $table) {
    // Nullable strings leave core data rules outside the database.
    $table->id();
    $table->integer('user_id')->nullable();
    $table->string('slug')->nullable();
    $table->string('status')->nullable();
    $table->text('body')->nullable();
});

Review Notes

What to review

Good Code

The good version gives the database enough information to reject orphaned reviews, duplicated slugs per user, and missing required fields.

Bad Code

The bad version treats every field as optional and omits relationships. Any importer, queue job, or admin script can insert invalid rows.

Takeaways

  • Important data rules should be enforced by the database, not only remembered by controllers or jobs.