Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pn523's avatar
Level 2

Duplicate key in table

In my Ecommerce database design, in Orders table I have customreId and ShipperId , both of them are stored in users table. Problem is when I reference foreign keys of both of them in orders table I get following error in migration :

 Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-555_19' (SQL: alter table `orders` add constraint `orders_user_id_foreign` foreign key (`user_id`) references `users` (`id`))

0 likes
5 replies
ftiersch's avatar

Can you show your migration? I think you might have an error in there.

$table->foreign('customer_id')->references('id')->on('users');
$table->foreign('shipper_id')->references('id')->on('users');

This would create the foreign keys.

pn523's avatar
Level 2

Here is my schema :

Schema::create('orders', function (Blueprint $table) {
   $table->bigIncrements('id');
   $table->unsignedBigInteger('product_id');
   $table->foreign('product_id')->references('id')->on('products');
   $table->unsignedBigInteger('user_id');
   $table->foreign('user_id')->references('id')->on('users');
   $table->unsignedBigInteger('shipper_id');
   $table->foreign('user_id')->references('id')->on('users');
   $table->timestamps();
});
Punksolid's avatar
Level 25

Man @pn

You have the exact sentence twice $table->foreign('user_id')->references('id')->on('users');

You error says explicitly

duplicate key in table '#sql-555_19' (SQL: alter table `orders` add constraint `orders_user_id_foreign

By duplicate it means that its trying to create another with the same name, and in the last part says orders_user_id_foreign that its the name of your foreign key by convention of laravel

pn523's avatar
Level 2

Thank you guys for all your help, I made such a stupid mistake

Please or to participate in this conversation.