0

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?

Carlos Tinnelly
  • 503
  • 1
  • 3
  • 20
  • Your question is a bit too unclear, please post you entire factory code, substituting the sensitive bits of course, by logic what you have shown should work – Dev Man Apr 16 '21 at 16:32

2 Answers2

3

I think what you're looking for is this: https://laravel.com/docs/8.x/database-testing#sequences

2

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.

panjezor
  • 118
  • 8
  • Is there a way to pass a parameter in the definition method of the factory? – Carlos Tinnelly Apr 16 '21 at 18:34
  • @CarlosTinnelly no, the factory comes up much sooner than the time to pass parameters. if you go for docs, there are directives for factories (cant recall exact name). – panjezor Apr 19 '21 at 08:32