0

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());
   });
});
Angga Ari Wijaya
  • 1,759
  • 1
  • 15
  • 31

1 Answers1

0

You can pass an array of attributes/values into the make method:

factory(App\Comment::class, rand(2, 10))->make(['user_id'=>$user->id]);

edit: just iterate over the comments and assign a random user id:

factory(App\Comment::class, rand(2, 10))->create()->each(function($comment){
   $comment->update(['user_id'=>\App\User::all()->random()->id]);
}); 

if you want to have random anonymous commenters:

factory(App\Comment::class, rand(2, 10))->create()->each(function($comment){
   // pick either a random user_id or null;
   $userId=array_random(\App\User::all()->random()->id, null);
   $comment->update(['user_id'=>$userId]);
});
Varol
  • 1,798
  • 1
  • 22
  • 30
  • `$user->id` actually post author, comment author could be anyone, and I use `saveMany` to create many comments in current post, so the result is all comments have same user_id. I consider use manual loop to insert many comments. – Angga Ari Wijaya Apr 04 '18 at 15:34