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

kfc's avatar
Level 1

error 150 "Foreign key constraint is incorrectly formed" laravel

Hi, I've been stuck with this error 150 "Foreign key constraint is incorrectly formed" though I have all the columns as the same type and length it won't work, my migration files:

Schema::create('discord_useres', function (Blueprint $table) {
            $table->id();
            $table->string('usr_email',255);
            $table->string('usr_id',255);
            $table->string("dis_usr");
            $table->string('dis_tag');
            $table->enum('verfied',[true,false]);
            $table->string('avatar');
            $table->timestamps();

        });

:

Schema::create('baskets', function (Blueprint $table) {
            $table->id();
            $table->string('usr_email',255);
            $table->string('usr_id',255);
            $table->timestamps();

            $table->foreign('usr_email')->references('usr_email')->on('discord_useres');
            $table->foreign('usr_id')->references('usr_id')->on('discord_useres');
        });

as I said it just won't work and give me this annoying error.

0 likes
4 replies
Nakov's avatar

The problem is that those are not unique so you cannot add a foreign key on whatever column you like. And also make sure that your database engine supports foreign keys on string data type.

Is the engine InnoDB for example?

You can add $table->engine = 'InnoDB'; in both migrations and it should work even for non-unique I think.

1 like
kfc's avatar
Level 1

@Nakov Thanks a lot for the answer u just saved me a headache

Tray2's avatar
Tray2
Best Answer
Level 73

@kfc That looks like a non optimal database design. One foreign key is enough between two tables (usr_id ), There is no need to have another column (usr_email) there as well. I also suggest the you connect the two tables using the primary key instead (id), that way you get better out of the box support from Laravel and you know that the value is unique.

1 like
lunfel's avatar

I had a really similar case and I want to share how I solved it.

In my case, I was adding a foreign key on a string type. Everything seemed to be same data type and data length. There was no error in the column name of anything. In the end, I was a bit out of ideas on how to solve it, so I just ran SHOW TABLE STATUS where Name in ('my_table_a', my_table_b'); to see if there was anything else different. I used a text diff software (Meld in this case) and I noticed that the table collation weren't the same.

One table had utf8mb4_unicode_ci and the other utf8_unicode_ci. In the end, I made sure both the charset AND the collation were the same and the error disappeared.

Please or to participate in this conversation.