How to seed a model that has a relationship to itself

Tags: , , ,

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


public function up()
    Schema::create('contests', function (Blueprint $table) {

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


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


public function run()
        '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?


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:


Source: stackoverflow