I tried to make a foreign key, however, it is not working.
Posts Migration
use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string("title", 60); $table->string("description", 200); $table->text("content"); $table->string("photo"); $table->unsignedBigInteger('user_id'); $table->timestamps(); $table->foreign("user_id")->references("id") ->on("users")->onDelete("cascade"); }); } public function down() { Schema::dropIfExists('posts'); } }
Users Migration
use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string("name", 30); $table->string("email")->unique(); $table->string("password"); $table->string("username")->unique(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } }
I am trying to make a “user_id” column for posts that should be connected with an id of a user via a foreign key. But, when I migrate I am getting errors like the following
IlluminateDatabaseQueryException
SQLSTATE[HY000]: General error: 1005 Can’t create table
mytest_db
.posts
(errno: 150 “Foreign key constraint is incorrectly formed”) (SQL: alter tableposts
add constraintposts_user_id_foreign
foreign key (user_id
) referencesusers
(id
) on delete cascade)at W:domainsmytest.uzvendorlaravelframeworksrcIlluminateDatabaseConnection.php:678 674▕ // If an exception occurs when attempting to run a query, we’ll format the error 675▕ // message to include the bindings with SQL, which will make this exception a 676▕ // lot more helpful to the developer instead of just the database’s errors. 677▕ catch (Exception $e) { ➜ 678▕ throw new QueryException( 679▕ $query, $this->prepareBindings($bindings), $e 680▕ ); 681▕ } 682▕
1
W:domainsmytest.uzvendorlaravelframeworksrcIlluminateDatabaseConnection.php:471 PDOException::(“SQLSTATE[HY000]: General error: 1005 Can’t create tablemytest_db
.posts
(errno: 150 “Foreign key constraint is incorrectly formed”)”)2
W:domainsmytest.uzvendorlaravelframeworksrcIlluminateDatabaseConnection.php:471 PDOStatement::execute()
Advertisement
Answer
Foreign keys cannot be defined on tables that don’t yet exist.
Laravel performs migrations in filename order, prepending timestamp to the migration name.
Make sure that CreatePostsTable
migration comes after the migration for CreateUsersTable
.