I have a table migration with a unique condition on item_id and user_id fields:
Schema::create('item_user', function (Blueprint $table) {
$table->id();
$table->foreignId('item_id')->references('id')->on('items')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->foreignId('user_id')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('CASCADE');
$table->boolean('active')->default(false);
$table->date('expires_at')->nullable();
$table->timestamps();
$table->unique(['item_id', 'active', 'user_id'], 'item_item_id_active_user_id_index');
});
I got error duplicate entry on item_id and user_id fields with factory.
class ItemUserFactory extends Factory
{
public function definition()
{
return [
'user_id' => $this->faker->randomElement(User::all())['id'],
'item_id' => $this->faker->randomElement(Item::all())['id'],
'active' => $this->faker->randomElement([0, 1]),
'expires_at' => $this->faker->dateTimeBetween('2 days', '1 month')
];
}
How can I fix it?
"laravel/framework": "^10.34.2",
"fakerphp/faker": "^1.23.0",
Set the user relation in the item model class and then in the factory try this: