Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Factory fails to eval models and factories when returned from closure #42344

Merged
merged 2 commits into from
May 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -448,22 +448,22 @@ protected function parentResolvers()
protected function expandAttributes(array $definition)
{
return collect($definition)
->map(function ($attribute, $key) {
->map($evaluateRelations = function ($attribute) {
if ($attribute instanceof self) {
$attribute = $attribute->create()->getKey();
} elseif ($attribute instanceof Model) {
$attribute = $attribute->getKey();
}

$definition[$key] = $attribute;

return $attribute;
})
->map(function ($attribute, $key) use (&$definition) {
->map(function ($attribute, $key) use (&$definition, $evaluateRelations) {
if (is_callable($attribute) && ! is_string($attribute) && ! is_array($attribute)) {
$attribute = $attribute($definition);
}

$attribute = $evaluateRelations($attribute);

$definition[$key] = $attribute;

return $attribute;
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ public function test_expanded_closure_attributes_are_resolved_and_passed_to_clos
$this->assertSame('taylor-options', $user->options);
}

public function test_expanded_closure_attribute_returning_a_factory_is_resolved()
{
$post = FactoryTestPostFactory::new()->create([
'title' => 'post',
'user_id' => fn ($attributes) => FactoryTestUserFactory::new([
'options' => $attributes['title'].'-options',
]),
]);

$this->assertEquals('post-options', $post->user->options);
}

public function test_make_creates_unpersisted_model_instance()
{
$user = FactoryTestUserFactory::new()->makeOne();
Expand Down