SQLSTATE[HY000]: General error: 1005 Can't create table `Projectname`.`users` (errno: 150 "Foreign key constraint is incorrectly formed")

Viewed 2560
Schema::create('projects', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

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

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->string('name');
    $table->timestamps();
});

When I run the php artisan migrate only the users table gets created then the migration process stops...

SQLSTATE[HY000]: General error: 1005 Can't create table Projectname.users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_project_id_foreign foreign key (project_id) references projects (id))

2 Answers

Look up your migration directory, you will see all your migration files, like 2014_10_12_000000_create_users_table

You are getting this error because your projects_create_table should be migrate before create_users_table file.

By default, laravel makes every migration file name by a date_time format, like 2014_10_12_000000_table_names.php So that, all files can be migrate serialwise.
So change your create_users_table file name with a date_time, so that can be migrate after projects_create_table, like :

2020_01_01_000000_create_projects_table.php
2020_01_01_000001_create_users_table.php

Now, if you run php artisan migrate, at first projects table will be created, then users table.

You used constrained() which tends to find table project or user Not projects or users. In that case you need to specify table name in constrained().

Schema::create('projects', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

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

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained('users');
    $table->string('name');
    $table->timestamps();
});

You can study more from here

Related