'Foreign Key Constraint Error in Laravel Migration
I have searched numerous questions on this error and cannot seem to fix it no matter what i try. This is my error:
Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table (SQL: alter table urls add constraint urls_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
My url table is as follows, i require the user_id column to reference id on the users table
public function up()
{
Schema::create('urls', function (Blueprint $table) {
$table->id();
$table->text('full_url');
$table->string('short_url')->unique();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
My original error was - '1452 cannot add or update a child row: a foreign key constraint fails' so I did php artisan migrate:refresh as i cannot see where the foreign key fails.
Solution 1:[1]
Laravel doc has a simpler version to create foreign keys.
Doc Link: https://laravel.com/docs/9.x/migrations#foreign-key-constraints
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
This came in laravel 7+
Solution 2:[2]
You have added the foreign key, But you didn't add the field itself.
So you should add:
$table->unsignedBigInteger('user_id');
to urls table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akhzar Javed |
| Solution 2 | Mojtaba Michael |
