[9.x] Allow seeders to be called only once #39812
Merged
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 adds a
callOncemethod to theSeederclass to call seeders only once (similar torequire_oncein PHP).This makes seeders more composable. Say you have an application with
PostandPagemodels, and they each can belong to aCategory.PostSeederandPageSeederexpectCategorySeederto run first to ensure there are categories in the database. TheDatabaseSeederrespects this order:However, you can't run
PageSeederorPostSeederon their own anymore. Moving$this->call(CategorySeeder::class)toPageSeederandPostSeederisn't a good solution either, because thenDatabaseSeederwill callCategorySeedertwice.With
callOnce, you call dependent seeders where there necessary.This enabled developers to cherry pick which seeders they want to run.
An alternative solution would be to add a
$beforeproperty to seeders.I opted for
callOncebecause it's consistent with the existingcallmethod, is more discoverable, and requires less changes.This is a non-breaking change, but I targeted it towards 9.x since it's a new feature and Laravel 9 isn't too far away. I'll rework this for 8.x it preferred.
I haven't added any tests yet because I want to discuss the API first. If this is something worth merging, I'll update the PR accordingly.