skip to Main Content

I’m working in a new Laravel 10 project running MySQL 8.0. I have two models: Campaign and MarketingList. Both models are owned by a User, but when trying to add a constrained() reference to user_id in each table I get the following error:

SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name ‘1’ (Connection: mysql, SQL: alter table marketing_lists add constraint 1 foreign key (user_id) references users (id))

It seems that MySQL can only have one or the other which isn’t my desired outcome since I want to always link things back to a User. What am I missing to resolve this? Here’s my two tables:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (! Schema::hasTable('campaigns')) {
            Schema::create('campaigns', function (Blueprint $table) {
                $table->uuid('id')->primary();
                $table->foreignUuid('user_id')->constrained()->index();
                $table->string('name');
                $table->tinyInteger('priority')->default(100);
                $table->dateTime('send_at');
                $table->timestamps();
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('campaigns');
    }
};

and…

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (! Schema::hasTable('marketing_lists')) {
            Schema::create('marketing_lists', function (Blueprint $table) {
                $table->uuid('id')->primary();
                $table->foreignUuid('user_id')->constrained()->index();
                $table->string('name');
                $table->timestamps();
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('marketing_lists');
    }
};

2

Answers


  1. Chosen as BEST ANSWER

    Ah, it looks like constrained() must come after other methods...

    $table->foreignUuid('user_id')->index()->constrained();
    

    Forgot that!


  2. Try removing the ->index() as I believe foreignUuid() automatically adds an index, and you are attempting to add a second duplicate index resulting in the error you mentioned.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search