I have some pre-seeded achievements in my DB that I'm not sure how to return via Laravel 8's factory. WebUser and Achievements have a Many-to-many relationship, which I also couldn't figure out from the docs on how to declare properly.
I'd like the WebUser to have an Achievement - that was returned from the DB randomly - attached to its relations via factories
I'm instantiating the WebUser like so:
$webUser = WebUsers::factory()
->has(Achievement::factory()->setClass('Onboarded'))
->create();
Because of the pre-seeded values, of course this throws an integrity constraint violation - duplicate entry - because the Achievements classes' names should be unique.
The WebUser's definition is simple:
public function definition()
{
return [
'web_user_id' => $this->faker->unique()->uuid,
'coins' => random_int(0, 1000),
'total_spins' => random_int(0, 100),
'total_wins' => random_int(0, 1000),
'total_loss' => random_int(0, 100)
];
}
My question is, how to write the Achievement factory in order not to create a new achievement, but rather return an already existing one from the DB.
AchievementFactory's state and definition are the following:
public function definition()
{
return [
'class' => $this->getRandomAchievementClass() // returns a random class name from existing ones
];
}
public function setClass($class)
{
return $this->state(function () use ($class) {
return [
'class' => $class
];
});
}