Search code examples
phplaravellaravel-5eloquentlaravel-seeding

Seeding relational data in Laravel eloquent database seeder / factory - Type error - Arg 1 should be Eloquent\Model - Collection given


I am trying to seed a table with relational data in a Laravel 5.5 application.

I have these two tables/models:

  • User
  • Question

On the app\User.php model file; I have the following hasMany relationship:

public function questions()
{
    return $this->hasMany(Question::class);
}

And Here's my database/factories/QuestionFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\Question::class, function (Faker $faker) {
    static $user_id;

    return [
        'user_id' => $user_id,
        'subject' => $faker->sentence(15),
        'body' => $faker->paragraph(3)
    ];
});

and my database/factories/UserFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('123456'),
        'remember_token' => str_random(10),
    ];
});

Given the above; I am trying to use it all in my dummy data seeder like this:

class DummyDataSeeder extends Seeder
{
    public function run()
    {
        // Seed dummy users
        factory(App\User::class, 10)->create()->each(function($user)
        {
            // With dummy questions
            $user->questions()->save(factory(App\Question::class, 3)->make());
        });
    }
}

The goal was to create 10 dummy users, and for each users to have 3 questions each.

When I seed the database with the above setup; I am getting the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\myapp.local\database\seeds\DummyDataSeeder.php on line 18


Solution

  • Try like this :

    factory(App\User::class, 10)->create()->each(function ($u) {
      $u->questions()->saveMany(factory(App\Question::class, 3)->make());            
    });