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

tejasgk's avatar

foreign key constraint incorrectly formed

I'm trying to migrate my DB and I get this error.

SQLSTATE[HY000]: General error: 1005 Can't create table waddle.posts (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table posts add constraint posts_user_id_foreign foreign key (user_id) references users (id) on delete cascade)

1 D:\tej\laravel\waddle\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table waddle.posts (errno: 150 "Foreign key constraint is incorrectly formed")")

2 D:\tej\laravel\waddle\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501 PDOStatement::execute()

I already tried foreign-key-constraint-is-incorrectly-formed-laravel and laravel-migration-errno-150-foreign-key-constraint-is-incorrectly-formed and I added unsigned to my Schema and it didnt work and I even tried adding users table above posts table(It worked and now I'm getting this error) .Here's my code for posts

       Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->text('title');
            $table->string('slug')->unique();
            $table->text('excerpt');
            $table->string('image')->nullable();
            $table->integer('user_id')->unsigned();
             $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

I'm using Laravel 9 edit sorry for late reply but I just created a new project and did the same and it worked perfectly maybe I might have made some error nd didnt know about it.Nevertheless I thank you all for helping begginers like me.

0 likes
6 replies
Nakov's avatar

If you are using Laravel 9, just do this:

$table->foreignId('user_id')->constrained()->cascadeOnDelete();

and remove this:

$table->integer('user_id')->unsigned(); 
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Nakov's avatar

@tejasgk you say you tried to add users table above posts table, isn't that the current order? The users table should exists before you create the posts and add a foreign key to that table.

And if you haven't touched the initial migration in terms of the primary keys, the above line should work 100%.

sr57's avatar

Does

  • table users has id as primary key?

  • field user_id from table waddle.posts is of type bigint ?

tejasgk's avatar

@sr57 it is just

$table->id();

in users table and post I tried unsignedBigInteger but still same error

Please or to participate in this conversation.