Laravel Factory ->each() add iterator

Viewed 6437

I have a factory:

    factory(Survey::class, 3)->create()->each(function ($survey)
    {
        factory(Question::class, 1)
            ->create()
            ->each(function ($question)
            {   
                factory(Option::class, rand(2,3))->create();
            });
    });

The problem is - I need to add an index to every option. It should be 1,2,3... How can I add iterator to ->each() function? I've tried to add variables inside body of the loop, but in not works as for/foreach one.

ANy ideas?

1 Answers

If I get your question right.

The each method iterates over the items in the collection and passes each item to a callback. If you will add second argument to each it will be an index of current element, which you can use later inside.

$collection->each(function ($item, $key) {
    //
});

https://laravel.com/docs/5.7/collections#method-each

Related