[13.x] feat: add randomOrFactory and randomOrFactoryCreate methods#60271
[13.x] feat: add randomOrFactory and randomOrFactoryCreate methods#60271calebdw wants to merge 1 commit into
Conversation
4e7c809 to
02493ac
Compare
02493ac to
c2fedcb
Compare
|
I believe this belongs more to the It could be It could be |
|
|
Then I don't see any problem in doing |
|
Thanks for your pull request to Laravel! Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include. If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions! |
Hello!
These are some factory helpers that I've been using for years in factories/seeders/tests and it was suggested that I upstream them.
There's many times that I want to grab a random model instead of always creating creating a new factory instance, but I don't want the code to fail if no records exist, some common use-cases:
Examples
final class CronLogFactory extends Factory { public function definition(): array { return [ - 'cron_id' => fn () => Cron::inRandomOrder()->first() ?? Cron::factory(), + 'cron_id' => fn () => Cron::randomOrFactory(), // ... ]; } }It also allow customizing the query or factory:
public function configure(): static { return $this->afterMaking(function (Contact $contact): void { - $contact->customer_id ??= Customer::query() - ->inRandomOrder() - ->engineering() - ->first()?->id - ?? Customer::factory() - ->engineering() - ->create()->id + $contact->customer_id ??= Customer::randomOrFactoryCreate( + fn ($q) => $q->whereEngineering(), + fn ($f) => $f->engineering(), + )->id; }); }Thanks!