You are probably trying to insert a big amount of fake datas and the fake data generator turns always around the same datas.
Jan 8, 2024
5
Level 1
Factory with some fields already into the DB
Hi
I'm using a Factory Class like this:
class TypeEventFactory extends Factory
{
protected $model = TypeEvent::class;
public function definition()
{
$type_event__name = ['A','B','C'];
return [
'name' => $this->faker->unique()->randomElement($type_event__name),
'description' => $this->faker->words(3, true),
];
}
}
It is called from an external Class with line:
$myArray = [
'type_event' => TypeEventFactory::new()->make()->name,
];
The problem is that the table type_event could not be empty (It contains some default values inserted from DB administrator) and one of the values A,B,C is already in the table type_event. If the Factory try to insert one of the existing value, return:
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint...
is there a way to use Factory with something like firstOrCreate() to check if the value already exists? If "no", insert and return Model inserted... if "yes" return the Model already in the DB.
Thank you
Please or to participate in this conversation.