Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HamidOsouli's avatar

create multiple comments for each user with faker php library and 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());
            });
0 likes
6 replies
rin4ik's avatar

with this?

factory(App\User::class, 50)->create()->each(function ($u) {
                $u->comments()->factory(App\Comment::class)->create();
            });
HamidOsouli's avatar

yes I create 50 users and for each user 1 comment. now I just want to create 3 comment for each user instead of 1

rin4ik's avatar
factory(App\User::class, 50)->create()->each(function ($u) {
                $u->comments()->factory(App\Comment::class, 3)->create();
            });
matthias.hertel's avatar
Level 4

you can make a loop in the foreach closure like this:

factory(App\User::class, 50)->create()->each(function ($u) {
        for ($x = 0; $x <= 2; $x++) {
                    $u->comments()->factory(App\Comment::class, 3)->create();
        }
});
1 like
HamidOsouli's avatar

thanks 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]);
}
1 like

Please or to participate in this conversation.