Hello, I'm new to Laravel, I started learning this week since I got a internship and I will learn PHP, Laravel and Codeigniter in there, so I wanted to get a head start.
I wanted to develop a simple recipes application, with recipes and reviews, but I'm currently having a problem when trying to seed the reviews table.
The problem I'm facing is when i try to seed it, I keep hitting the unique constraint created to assure that a user only creates one review per recipe, even when trying to handle the duplication.
Currently my reviews table is:
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(User::class); // Foreign Key to the author of the review.
$table->foreignIdFor(Recipe::class); // Recipe receiving the review.
$table->tinyInteger("score");
$table->string("title");
$table->text("description");
$table->timestamps();
$table->unique(["user_id", "recipe_id"]);
});
I tried to add some verifications before returning the factory definition, but it still gives errors.
The current factory logic is:
public function definition(): array
{
// Get a random recipe and a random user different than it's author.
$recipe = Recipe::inRandomOrder()->first() ?? Recipe::factory()->create();
$user_id = User::all()->where('id', '!=', $recipe->user_id)->random()->id;
// Counter of tries to create a valid review.
$cur_count = 0;
// Assure that the user doesn't have a review for that recipe.
while (Review::where('user_id', $user_id)
->where('recipe_id', $recipe->id)->exists()
) {
// Increments the counter and create a new user if doesn't find a valid user.
if (++$cur_count == 3) {
$user_id = User::factory()->create();
break;
}
// Get a new random user.
$user_id = User::where('id', '!=', $recipe->user_id)
->where(
'id',
'!=',
$user_id
)->random()->id;
}
return [
'user_id' => $user_id,
'recipe_id' => $recipe->id,
'title' => fake()->slug(),
'description' => fake()->paragraph(),
'score' => fake()->numberBetween(0, 10)
];
}
I'm getting: SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "reviews_user_id_recipe_id_unique" DETAIL: Key (user_id, recipe_id)=(27, 9) already exists.
I would be really thankful if someone could give me a idea on how to make it work. Thanks in advance.