1
votes

I have User and Activity models. User hasMany relationship to Activity (and an Activity belongsTo only one User):

In User model:

public function activities() {
    return $this->hasMany(Activity::class);
}

I want to seed the users with their corresponding activities. I tried this but did not work:

public function run()
{
    factory(App\User::class, 5)->create()->each(function ($user) {
        $user->activities()->saveMany(factory(App\Activity::class, 2)->make());
    });
}

ActivityFactory:

$factory->define(App\Activity::class, function (Faker $faker) {
    return [
        'title'        => $faker->text(50),
        'description'  => $faker->text(200)
    ];
});

What am I doing wrong?

1
Please can you show the factory for the Activity model.Rwd
@RossWilson i added it. thanks!user1506104

1 Answers

2
votes

Try this way:

database/factories/ActivityFactory.php

$factory->define(App\Activity::class, function (Faker\Generator $faker) {
    return [
        'user_id' => factory('App\User')->create()->id,
        'title'        => $faker->text(50),
        'description'  => $faker->text(200),
    ];
});

database/seeds/ActivitySeeder.php

public function run()
{
    factory(App\Activity::class, 10)->create();
}

And then run for the activity seed.

php artisan make:seeder ActivitySeeder