Skip to content

Commit 0d00d04

Browse files
authored
pass attributes and parent arguments to Factory Sequence as in ->state() (#56972)
1 parent 7f67479 commit 0d00d04

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/Illuminate/Database/Eloquent/Factories/Sequence.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,13 @@ public function count(): int
5151
/**
5252
* Get the next value in the sequence.
5353
*
54+
* @param array<string, mixed> $attributes
55+
* @param \Illuminate\Database\Eloquent\Model|null $parent
5456
* @return mixed
5557
*/
56-
public function __invoke()
58+
public function __invoke($attributes = [], $parent = null)
5759
{
58-
return tap(value($this->sequence[$this->index % $this->count], $this), function () {
60+
return tap(value($this->sequence[$this->index % $this->count], $this, $attributes, $parent), function () {
5961
$this->index = $this->index + 1;
6062
});
6163
}

tests/Database/DatabaseEloquentFactoryTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,39 @@ public function test_counted_sequence()
533533
$this->assertSame(3, $value);
534534
}
535535

536+
public function test_sequence_with_has_many_relationship()
537+
{
538+
$users = FactoryTestUserFactory::times(2)
539+
->sequence(
540+
['name' => 'Abigail Otwell'],
541+
['name' => 'Taylor Otwell'],
542+
)
543+
->has(
544+
FactoryTestPostFactory::times(3)
545+
->state(['title' => 'Post'])
546+
->sequence(function ($sequence, $attributes, $user) {
547+
return ['title' => $user->name.' '.$attributes['title'].' '.($sequence->index % 3 + 1)];
548+
}),
549+
'posts'
550+
)
551+
->create();
552+
553+
$this->assertCount(2, FactoryTestUser::all());
554+
$this->assertCount(6, FactoryTestPost::all());
555+
$this->assertCount(3, FactoryTestUser::latest()->first()->posts);
556+
$this->assertEquals(
557+
FactoryTestPost::orderBy('title')->pluck('title')->all(),
558+
[
559+
'Abigail Otwell Post 1',
560+
'Abigail Otwell Post 2',
561+
'Abigail Otwell Post 3',
562+
'Taylor Otwell Post 1',
563+
'Taylor Otwell Post 2',
564+
'Taylor Otwell Post 3',
565+
]
566+
);
567+
}
568+
536569
public function test_cross_join_sequences()
537570
{
538571
$assert = function ($users) {

0 commit comments

Comments
 (0)