[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
callOnce
method to theSeeder
class to call seeders only once (similar torequire_once
in PHP).This makes seeders more composable. Say you have an application with
Post
andPage
models, and they each can belong to aCategory
.PostSeeder
andPageSeeder
expectCategorySeeder
to run first to ensure there are categories in the database. TheDatabaseSeeder
respects this order:However, you can't run
PageSeeder
orPostSeeder
on their own anymore. Moving$this->call(CategorySeeder::class)
toPageSeeder
andPostSeeder
isn't a good solution either, because thenDatabaseSeeder
will callCategorySeeder
twice.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
$before
property to seeders.I opted for
callOnce
because it's consistent with the existingcall
method, 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.