Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

paypip's avatar
Level 1

How to set null value of specific factory record?

Hi,

In my user seeder, I want to create 10 experiences for each user. Now for one experience (at least) I need to set a end_date null. I am not sure how to do this.

Experience::factory()->create([
    'user_id' => $user->id,
    'end_date' => null, // 9 out of 10 experiences will have a end_date now() and 1 will have a null end_date
]);

Any suggestion?

0 likes
5 replies
tykus's avatar

You can get creative with a Sequence index, e.g.

User::factory()
    ->has(
      Experience::factory()
        ->count(10)
        ->sequence(fn ($sequence) => ['end_date' => ($sequence->index + 1)  < 10 ? now() : null])
    )->create();
1 like
paypip's avatar
Level 1

@tykus Thanks for answer, but it does not work as expected. I want 1 experience is null and 9 experience have value. Unfortunately your solution provide first 9 has value, and then all of them are empty.

here what I tried so far:

User::factory(10)
    ->has(
      Experience::factory()
        ->count(10)
        ->sequence(fn ($sequence) => ['end_date' => ($sequence->index + 1)  < 10 ? now() : null])
    )->create();
tykus's avatar

@paypip just change the implementation; to allow for multiple parent records (which was not apparent from the orginal question, nor my solution):

User::factory(10)
    ->has(
      Experience::factory()
        ->count(10)
        ->sequence(fn ($sequence) => ['end_date' => ($sequence->index %10 ? null : now()])
    )->create();

tisuchi's avatar
tisuchi
Best Answer
Level 70

@paypip you can use the collect helper function also, for example:


collect(range(1, 10))->each(function ($index) use ($user) {
                Experience::factory()->create([
                    'user_id' => $user->id,
                    'end_date' => $index === 1 ? null : now(),
                ]);
            });
1 like

Please or to participate in this conversation.