4

I'm modeling and seeding the following models using Laravel 9 and Eloquent:

  • Organization (1-n)
  • organizations_users (pivot)
  • User (1-n)

To seed that model, I followed the documentation and used has() and recycle() methods.

database/seeders/DatabaseSeeder.php

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // Organisations et users
        $organizations = Organization::factory()
            ->count(10)
            ->create();

        $users = User::factory()
            ->recycle($organizations)
            ->has(Organization::factory()->recycle($organizations)->count(1))
            ->count(10)
            ->create();
    }

When I run the migration with ->has(Organization::factory()->count(1)), I'm getting 20 organizations in database instead of 10.

It seems the Organizations are not recycled for the relationships and a new Organization is created for each relationship.

What am I doing wrong? Am I able to seed the relations on a separate call after having seeded the users and the organizations?

maxime
  • 1,993
  • 3
  • 28
  • 57
  • Did you manage to figure it out? I'm stuck in a similar situation. Chaining those requests seems to be failing. – BkiD Feb 02 '23 at 06:41
  • 1
    I ended up creating models without factories but directly with Faker and loops. It is not pretty like in the doc, but it solves the issue – maxime Feb 02 '23 at 20:25

1 Answers1

1

You can use afterCreating on UserFactory and create random relationship manually.

DatabaseSeeder

public function run()
{
    Organization::factory()
        ->count(10)
        ->create();

    User::factory()
        ->count(10)
        ->create();
}

UserFactory

public function configure()
{
    return $this->afterCreating(function (User $user) {
        $user->organizations()->attach(Organization::all()->random(3));
    });
}

Each user will have random 3 organizations that have been created before.

Nurul Huda
  • 1,438
  • 14
  • 12