Laravel Factory: Adding Iterators and Indices to Nested Data Generation

Laravel Questions editorial team
Editorial team · 15 October 2026

You seed a survey with questions, and each question with options, and want the options numbered 1, 2, 3 inside every question.

Number one level with Sequence

use Illuminate\Database\Eloquent\Factories\Sequence;

SurveyQuestion::factory()
    ->count(4)
    ->state(new Sequence(fn (Sequence $sequence) => ['position' => $sequence->index + 1]))
    ->create(['survey_id' => $survey->id]);

$sequence->index starts at 0, so add 1. The positions come out as 1, 2, 3, 4.

Restart the count for every parent

A single Sequence object keeps counting for as long as you reuse it. If you share one across two questions, the second question’s options start at 3, not 1. Create a fresh factory (and so a fresh Sequence) per question. afterCreating gives you each question as it is made:

SurveyQuestion::factory()
    ->count(3)
    ->state(new Sequence(fn (Sequence $s) => ['position' => $s->index + 1]))
    ->afterCreating(function (SurveyQuestion $question) {
        QuestionOption::factory()
            ->count(3)
            ->state(new Sequence(fn (Sequence $s) => ['position' => $s->index + 1]))
            ->create(['question_id' => $question->id]);
    })
    ->create(['survey_id' => $survey->id]);

Every question ends up with options 1, 2, 3.

Why a counter variable fails

A $i++ captured by a closure inside each() is not reset when the outer loop moves on. Sequence keeps its own index for the factory it is attached to, which is why a new one per parent restarts at 0.

Tested on Laravel 10.x (PHP 8.1) and 12.x (PHP 8.3): the tests check positions 1 to 4 for questions, 1 to 3 for the options of each of three questions, and that a shared Sequence continues counting (3, 4). Source: tests/laravel-verification/files/q9462.

Our network