Skip to content
Advertisement

Factory creating multiple models with different number of relationships

I’m using the following code to create 20 posts, each of which has 3 comments.

Post::factory()
    ->times(20)
    ->has(Comment::factory()->times(3))
    ->create()

Instead I’d like to create 20 posts, each of which has a random number of comments (e.g. post 1 has 2 comments, post 2 has 4 comments, etc.)

This did not work, each post had the same (random) number of comments.

Post::factory()
    ->times(20)
    ->has(Comment::factory()->times(rand(1, 5)))
    ->create()

How can I achieve this?

Advertisement

Answer

It’s not possible to have a dynamic number of related models per model if you are using ->times as far as I know. You can instead try:

collect(range(0,19))
   ->each(function () {
       Post::factory()
          ->has(Comment::factory()->times(rand(1,5)))
          ->create();
});

This should create 20 posts one by one with a random number of comments on each. It may be a bit slower but probably not by much

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement