Skip to content
Advertisement

How to seed a model that has a relationship to itself

I am using Laravel 8 and PHP v7.4 I have a model with a schema generated with the below migration.

CreateContestsTable

public function up()
{
    Schema::create('contests', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->foreignId('contest_id')->nullable();
        $table->foreign('contest_id')->references('id')->on('contests');
    });
}

A contest can have many contests. To seed this, I have generated a factory class.

ContestFactory

public function definition()
{
    return [
        'name' => $this->faker->paragraph(),
    ];
}

ContestSeeder

public function run()
{
    AppModelsContest::factory(10)->create([
        'contest_id' => array_rand(AppModelsContest::all()->pluck('id')->toArray())
    ]);
}

The above throws the following error.

ErrorException array_rand(): Array is empty

How can I solve this problem?

Advertisement

Answer

The records have not been created yet when you do the query to pluck the information. You can call create() with no arguments so it creates the records then you can iterate the returned Collection:

AppModelsContest::factory(10)->create()->each(...);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement