[9.x] Allow factories to recycle multiple models of a given type #44328
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR is an enhancement to recently added feature, Eloquent Factory recycling (#44107) and adds support for recycling multiple models of the same type.
Model recycling is a great feature, making factories much cleaner and easier to write. While recycling a single model has its valid use cases, it doesn't really help if we want to create multiple models (
->count(10)
) with our factory - all of them will be related to that same model.This PR allows developers to provide their own, already created pool of models (collections), so they could be reused in all nested relations. For each relation, factory class picks a random model from a provided collection of models, instead of depending on a single one.
Sample usage:
For example, we often see that the User model relates to everything - as an author of some content, comments, reactions, performed operations etc. In more complex applications, that nesting can go deep. In that scenario, much easier would be to seed a number of users once and then reuse them in all nested relations (so we don't create a user only to be the author of a single comment). It's then closer to a real-life case, where we could have a set number of users in the system and all the actions performed and content created is within that group.
This approach leads to cleaner factories, less database pollution and overall higher seeding quality - created models will be much more related to each other.
New recycle method still allows for providing a single model so the PR is backward-compatible, without any breaking changes.