Are you using SQLite? Are foreign keys enabled?
PRAGMA foreign_keys = ON;
I just have a fresh Laravel 9 (latest) installation. I have made some migrations successfully and tried to add foreign key constraints, but Laravel's not creating the actual Foreign Key itself. It doesn't throw any errors and I can query everything just fine, but no Foreign key is being created.
What's strange is that I've simply copied the Migration code from one of my older projects. Here is the 2 migration Schema:
Schema::create('users', function (Blueprint $table)
{
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('posts', function (Blueprint $table)
{
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('name');
$table->timestamps();
});
When I do the migration I get an index called posts_user_id_foreign but no Foreign Key is being added.
I have already tried the following variations on the Posts table with no success:
$table->foreignId('user_id')->constrained('users');
-----
$table->foreignId('user_id')->constrained('users')->onUpdate('cascade');
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
-----
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
Can anyone please tell me why is this happening and what's the solution? I had no issues creating Foreign Key before with Laravel. Not sure what's changed now in the latest version...
Please or to participate in this conversation.