0
votes

SQLSTATE[HY000]: General error: 1005 Can't create table project.#sql-4b4_46 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table projects add constraint projects_owner_id_foreign foreign key (owner_id) references users (id) on delete cascade)

 Schema::create('projects', function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->unsignedInteger('owner_id');
                    $table->string('title');
                    $table->text('description');
                    $table->timestamps();
                    $table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
                    });
    Schema::create('users', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
3
The issue might be due to creation ordering of projects and users tables. Try creating the users table before defining schema create for projects. Also, the projects.owner_id could be bigInteger type to match the bigIncrements for users.id.Igor

3 Answers

0
votes

Create users table first, then create projects table and assign foreign key to users.

0
votes

You have to use unsignedBigInteger when using foreign keys

$table->unsignedBigInteger('owner_id');

And, surely, you have to create the target table first 😉 So, create users first and after that create projects

0
votes

If the primary key is using unsignedBigInteger, the foreign key should also be using unsignedBigInteger.

     Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
     });

   Schema::create('projects', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedBigInteger('owner_id');
                $table->string('title');
                $table->text('description');
                $table->timestamps();
                $table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
   });