Reputation: 579
I've got a Factory definition like this:
public function definition() {
$to = $this->faker->numberBetween(1, 3);
return [
"ad_id" => $to == 1 ? Ad::all()->random()->id : null,
"delivery_id" => $to == 2 ? Delivery::all()->random()->id : null,
"group_event_id" => $to == 3 ? GroupEvent::all()->random()->id : null,
];;
}
Basically, there are 3 fields, but just one can be defined, if one is defined, the others must be null, the factory uses faker to decide it, but now, I want to set which I want from the seeder:
MyModel::factory()->create([
"ad_id" => null,
"delivery_id" => 5,
"group_event_id" => null,
]);
But this doesn't work, the factory ignore my null parameters that I'm passing for the other fields and set random Id's for the both null parameters. How can I solve it?
Upvotes: 0
Views: 1382
Reputation: 72
I think what you're looking for is this: https://laravel.com/docs/8.x/database-testing#sequences
Upvotes: 3
Reputation: 138
You basically need to make that check prior to calling the factory. You cannot pass a value so that factory would read it and process it, unfortunately its the other way around, so the factory makes a template and that gets then overwritten by the values from the array that you pass over in make/create functions, so the only thing you can do is make that check before calling creation and fill that in.
Upvotes: 2