Laravel - Database - Sequences

Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an admin column between Y and N for each created user:

    
    use App\Models\User;
    use Illuminate\Database\Eloquent\Factories\Sequence;
    
    $users = User::factory()
                    ->count(10)
                    ->state(new Sequence(
                        ['admin' => 'Y'],
                        ['admin' => 'N'],
                    ))
                    ->create();
	

In this example, five users will be created with an admin value of Y and five users will be created with an admin value of N.

If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value:

    
    $users = User::factory()
                    ->count(10)
                    ->state(new Sequence(
                        fn ($sequence) => ['role' => UserRoles::all()->random()],
                    ))
                    ->create();
	

Within a sequence closure, you may access the $index or $count properties on the sequence instance that is injected into the closure. The $index property contains the number of iterations through the sequence that have occurred thus far, while the $count property contains the total number of times the sequence will be invoked:

    
    $users = User::factory()
                    ->count(10)
                    ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])
                    ->create();