0

I want to use two models on my laravel 7.x application : Users and Images :

# Users migration : 2014_10_12_000000_create_users_table.php

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

# Images migration : 2020_03_27_121254_create_models_images_table
Schema::create('images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned;
        $table->string('name');
        $table->timestamps();
    });

    Schema::table('images', function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

When trying to migrate i receive following error : General error: 1215 Cannot add foreign key constraint (SQL: alter table images add constraint images_user_id_foreign foreign key (user_id) references users (id) on delete cascade)

I have already searched over google without success, someone could helps me please ?

Thank you

miken32
  • 42,008
  • 16
  • 111
  • 154
  • Does this answer your question? [Migration: Cannot add foreign key constraint](https://stackoverflow.com/questions/22615926/migration-cannot-add-foreign-key-constraint) – miken32 May 09 '23 at 16:29

2 Answers2

1

Problem

You are not setting the unsigned properly.

Solution

Replace:

$table->bigInteger('user_id')->unsigned;

By:

$table->bigInteger('user_id')->unsigned();

Explanation

Since the user_id is not unsigned, the definition does not match the id of the users table which means you cannot set the foreign key.

Before Laravel 7.x

You could also do:

$table->unsignedBigInteger('user_id');

Laravel 7.x

As of Laravel 7, you can do it like this in your users migration:

Schema::table('users', function (Blueprint $table) {
    $table->id();
    // ...
});

And in your images migration:

Schema::table('users', function (Blueprint $table) {
    // ...
    $table->foreignId('user_id')->constrained();
});

You can find more information here: https://laravel.com/docs/7.x/migrations#foreign-key-constraints

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
0

You are missing bracket in unsiged()

As per Laravel Documentation

->unsigned() Set INTEGER columns as UNSIGNED (MySQL)

Change

 $table->bigInteger('user_id')->unsigned;

to

$table->bigInteger('user_id')->unsigned();
Sehdev
  • 5,486
  • 3
  • 11
  • 34