6

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?

Denys Siebov
  • 198
  • 4
  • 16

1 Answers1

11

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

Volod
  • 1,283
  • 2
  • 15
  • 34