Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Seeding Multiple Tables That Effect Each Other

I have a table for players with a timestamp field called signed_on. I have 3 other tables in my DB called injuries, retirements, suspensions. What I'm trying to do is seed the 3 other tables. My issue is obviously that a player can't be injured, retired, or suspension during any of the other possibilities. Also, the date those started on has to be after the signed_on date. Any thoughts on how I should handle this in a seed(s) file.

0 likes
1 reply
ftrillo's avatar

I'd recommend making a Factory for each model. https://laravel.com/docs/5.5/database-testing#writing-factories

Faker docs: https://github.com/fzaninotto/Faker

This is a rough look at how the Player factory might be.

$factory->define(App\Player::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name, // random name
        'sign_on' => $faker->date,
    ];
}

Of course, your factory might be different depending on your database structure.

After the factories are done you can generate 100 players in the seeder like this:

factory(Player::class, 100)->create()->each(function($player) {
    // Here you generate the random dates that you need for the other models
    
    $player->injuries()->save(factory(Injury::class)->create([/* Here you pass the desired dates for the injury model */]));
    // Do the same with the other related models
});

Please or to participate in this conversation.