Laravel : using model factories to generate one-to-many relationships

Your Models & Model Factories seem fine, but use them with this seeder instead:

use Illuminate\Database\Seeder;

class ClubSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Club::class, 100)->create()->each(function($c) {
            /** @var \App\Club $c */
            $c->fixtures()->saveMany(
                factory(App\ClubFixture::class, 5)->make(['club_id' => NULL])
            );
        });
    }
}

Make sure you call the saveMany() method on the fixtures() relationship method of your Club model. Finally also override the club_id for each iteration of the 5 ClubFixtures to prevent another creation of a Club. Otherwise you'd end up with 600 Clubs (instead of 100 Clubs) & 500 ClubFixtures.


You should do this

'club_id' => function () {
            return factory(App\Club::class,5)->create()->id;
        },

for the ClubFixture factory.


Try this

Modal Factories

$factory->define(App\Club::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'league' => $faker->word,
        'age_group' => $faker->word,
        'colour' => $faker->hexcolor,
        'county' => $faker->state,
        'country' => $faker->country,
        'emblem' => $faker->imageUrl(80, 80),
        'banner' => $faker->imageUrl,
        'matches' => $faker->randomDigit,
        'wins' => $faker->randomDigit,
        'losses' => $faker->randomDigit,
    ];
});

$factory->define(App\ClubFixture::class, function (Faker\Generator $faker) {
    return [
        'club_id' => function () {
            return factory(App\Club::class,5)->create();
        },
        'opposition' => $faker->name,
        'address' => $faker->address,
        'datetime' => $faker->dateTimeBetween('now', '+30 weeks'),
        'type' => $faker->randomElement(['home', 'away', 'none']),
    ];
});