skip to Main Content

In ListingFactory.php I have something like this

return [
    'reviews' => json_encode([
        'user' => fake()->name(),
        'body' => fake()->paragraph(),
    ]),
]

Additionally, in the DatabaseSeeder.php I have this at the moment

AppModelsListing::factory(10)->create();

The current problem is that it will always generate one instance of review. What I want is a random number of reviews in a range.

For example, right now the table column of Review will always be [{}], I want something like [{}, {}, {}] or [].

3

Answers


  1. Simply generate your fake data in loop.

    $reviews = [];
    
    foreach(range(1,10) as $i) { // f.e. run it 10 times
      $reviews[] = [
         'user' => fake()->name(),
         'body' => fake()->paragraph(),
      ]
    }
    
    return [
          "reviews" => json_encode($reviews),
     ]
    
    Login or Signup to reply.
  2. I would believe that randomElements() can do what you want, it takes x elements from a sequence. Combine that with a random number and you would achieve that.

    json_encode(fake()->randomElements(
        [
            [
                'user' => fake()->name(),
                'body' => fake()->paragraph(),
            ],
            [
                'user' => fake()->name(),
                'body' => fake()->paragraph(),
            ],
            [
                'user' => fake()->name(),
                'body' => fake()->paragraph(),
            ],
        ],
        random_int(1, 3),
    )),
    

    If you would change the amount of reviews, increase random_int(1, 10) for a sequence of 10.

    Login or Signup to reply.
  3. Don’t make it complicated. Just generate a random number and then generate that many reviews.

    $reviews = [];
    $amount = rand(1,10);
    
    for($x = 0; $x < $amount; $x++ ){
       $reviews[] = [
            'user' => fake()->name(),
            'body' => fake()->paragraph(),
        ];
    }
    
    
    return [
        "reviews" => json_encode($reviews),
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search