Seeding multiple foreign key records using model factories

Published 1 year ago by Refringe

I have a User and Team model factory and I'm using a seeder to populate the database. However, I'm trying to ensure that each user that I add has two teams.

This works, but because I'm repeating a line entirely, it feels... dirty?

factory(App\User::class, 30)->create()->each(function ($user) {
    $user->teams()->save(factory(App\Team::class)->make());
    $user->teams()->save(factory(App\Team::class)->make());
});

Is there a more efficient way to do this? It's not a huge deal now, but I'm going to be using this same method to add 20+ child records to a parent with other models and I want to be sure I'm doing it right.

Here are my two factories, if it helps at all:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'firstname' => $faker->firstname,
        'lastname' => $faker->lastname,
        'email' => $faker->safeEmail,
        'password' => bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Team::class, function(Faker\Generator $faker) {
    return [
        'user_id' => $faker->randomElement(App\User::pluck('id')->toArray()),
        'name' => $faker->company,
    ];
});
Best Answer (As Selected By Refringe)
ctroms

You can do what you did when creating 30 users but change your save method to saveMany.

factory(App\User::class, 30)->create()->each(function ($user) {
    $user->teams()->saveMany(factory(App\Team::class, 2)->make());
});

It saves a line of code anyway.

ctroms
ctroms
1 year ago (59,850 XP)

You can do what you did when creating 30 users but change your save method to saveMany.

factory(App\User::class, 30)->create()->each(function ($user) {
    $user->teams()->saveMany(factory(App\Team::class, 2)->make());
});

It saves a line of code anyway.

Refringe

That's exactly what I was looking for. Thank you!

Refringe

Is there a way to go one step deeper and create (say 10) of App\Player for each of the two teams that are created per user?

Please sign in or create an account to participate in this conversation.