Search code examples
phplaravelfaker

create multiple comments for each user with faker php library model factories


I want to generate fake data with faker PHP library but I want for example create 3 comments for each user. How should I do this?

I do create 1 comment for each user with this code :

factory(App\User::class, 50)->create()->each(function ($u) {
    $u->comments()->save(factory(App\Comment::class)->make());
});

Solution

  • I found the solution :)

    I used dd(factory(Comment::class,mt_rand(0,3))->make()) and I found that it returns the collection of 3 comments that is been created so I used foreach to create all of these 3 comments for my user using these lines of code :

    $comments = factory(Comment::class,mt_rand(0,3))->make();
      for ($i=0; $i < $comments->count(); $i++) { 
      $u->comments()->save($comments[$i]);
    }