Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Factory – generate fake json array data with random amount of iterations in a single column

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

        \App\Models\Listing::factory(10)->create();

Any assistance is greatly appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 [].

>Solution :

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),
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading