Skip to content

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

Merged
taylorotwell merged 2 commits into
laravel:9.xfrom
harrygulliford:factory-resolves-closure-attribute-returning-factory
May 11, 2022
Merged

taylorotwell merged 2 commits into
laravel:9.xfrom
harrygulliford:factory-resolves-closure-attribute-returning-factory

Conversation

@harrygulliford

@harrygulliford harrygulliford commented May 11, 2022 •

Copy link
Copy Markdown
Contributor

Since v9.12.0, due to the changes made in #42241, model factories now fail to evaluate both models and factories when they are returned from a closure.

This is due to models and factories now being resolved first and closures second.

To fix this issue, while maintaining the functionality added in #42241, the resolution of models and factories would need to be repeated again after resolving closures.

A rudimentary example:

class PostFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => 'post',
            'user_id' => function (array $attributes) {
                return User::factory(['options' => $attributes['title'].'-options']);
            },
        ];
    }
}

In the latest release, the code above would throw an exception - occurring when the database driver attempts to bind a factory object the query statement (see failing test).

Error: Object of class \Database\Factories\PostFactory could not be converted to string

@harrygulliford harrygulliford changed the title [9.12.0] Factory fails to eval models and factories when returned from closure [9.x] Factory fails to eval models and factories when returned from closure May 11, 2022
@taylorotwell
taylorotwell merged commit 4ebd79d into laravel:9.x May 11, 2022
salmanarshad321 pushed a commit to salmanarshad321/framework that referenced this pull request Sep 23, 2026
…losure (laravel#42344)

* Add test to check a factory closure attribute returning a factory is resolved

* Fix evaluation of factories and models when returned from a closure in factory definition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants