I tried to make a foreign key, however, it is not working.
Posts Migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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 Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
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
Illuminate\Database\QueryException
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:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.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:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create tablemytest_db
.posts
(errno: 150 "Foreign key constraint is incorrectly formed")")2
W:\domains\mytest.uz\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471 PDOStatement::execute()
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
.