I have tables users
, posts
, and comments
, a user has many posts, each post has many comments (post_id
in comments table), also a user has many comments but not fully required for anonymous user (user_id
in comment table), code below seed each post with some comments but user_id is never filled by the owner of comment. I want the comment has related user_id by injecting in array outside $factory->define
. Actually I could put random user_id inside factory but total random user must be the same value in Seeder class.
**CommentFactory.php**
$factory->define(App\Contact::class, function (Faker $faker) {
return [
// 'user_id' => $faker->randomElement([null, rand(0, 9)]),
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'contact' => $faker->phoneNumber,
'website' => $faker->domainName,
'subject' => $faker->sentence(),
'message' => $faker->paragraph(5),
];
});
**UserSeeder.php**
factory(App\User::class, 10)->create()->each(function ($user) {
$user->posts()->saveMany(factory(App\Post::class, rand(2, 10))->make());
$user->posts->each(function ($post) use ($user) {
// how to inject user_id value from here (comment factory)
$post->comments()->saveMany(factory(App\Comment::class, rand(2, 10))->make());
});
});