-
Notifications
You must be signed in to change notification settings - Fork 11.1k
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
[8.x] Add support for attaching existing model instances in factories #35494
[8.x] Add support for attaching existing model instances in factories #35494
Conversation
Attach existing models in factories
@bakerkretzmar just wanted to note in your first example there will not be 10 users... there will be 1... $posts = Post::factory(10)
->for(User::factory()->state(['admin' => true]))
->create(); |
@taylorotwell yep sorry you're right, updated the example! I think I got that mixed up with using factories inside other factory definitions. |
Looks like there's an issue with this, we missed a couple places where we need to check the type to get the class name. Looking into it now and will PR a fix. |
@bakerkretzmar One more place that was missed is in the magic method handling for when the relationship name is different than the model name. e.g. $posts = Post::factory(10)
->forOtherUser($user = User::factory()->create())
->create();
assert($posts->every(fn ($post) => $post->otherUser->is($user))); Looks like it's a simple fix for return $this->for($parameters[0] instanceof Factory ? $factory->state($parameters[0] ?? []) : $parameters[0], $relationship); Not sure if this should also extend to |
@bakerkretzmar I just saw this PR, I was pretty busy the last few months. I'm glade you took the initial idea from my PR and made it much better ! 🔥 Thanks a lot ! |
TL;DR: adds support for passing Eloquent model instances, or collections of model instances, into the
for()
andhasAttached()
factory methods.Sometimes when creating models in a test, we need to be able to attach existing model instances to them instead of relying on the relation's factory. Currently the way to do this is to create all the models separately and then relate them manually, or to pass the column name and ID of the existing models into a factory's state or
create()
method.This PR makes attaching existing models more straightforward. It's similar to #34539, but focuses on making the
for()
andhasAttached()
methods more flexible and doesn't add any new methods.BelongsTo / MorphTo
Before
After
BelongsToMany / MorphToMany
Before
The alternative to this, right now, is to create the users and roles separately and then attach them manually:
After