When using foreign keys seed the dependent records first

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

Last Updated: 2021-05-15

I ran into errors when seeding the database in Laravel.

<?php

// AdvisorSeeder.php
DB::table('advisors')->insert([
  'id' => 1,
  'user_id' => 4,
  "gender" => "female",
  "title" => "Taxwoman",
])

// UserSeeder.php
DB::table('users')->insert([
  'id' => 4,
  'email' => "me@example.com",
])

Later, when I had a test setup that called the AdvisorSeeder, it failed. That was because it referenced a non-existent foreign key, the user with id=4. I needed to have already seeded the users table for this connection to a foreign key to work.

Lesson

The foreign key targets must be seeded before the records that reference the foreign keys.