Write migrations with foreign key dependencies first

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the workflows category.

Last Updated: 2024-12-03

When generating migrations, always do them with a mind to foreign key dependencies.

With Project X, I created the following migration for the slots table before generating the station_locations table migration.

<?php
Schema::create('slots', function (Blueprint $table) {
    $table->id();
    $table->dateTime('start_time', 0)->index();
    $table->foreignId('station_location_id')->constrained();
    $table->timestamps();
});

This migration would not run because it made reference to station_location_id, a foreign key which didn't exist yet.

I should have put some thought into how to order my migrations first.