Home > Software engineering >  Foreign Key Constraint Error in Laravel Migration
Foreign Key Constraint Error in Laravel Migration

Time:05-18

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related