laravel 8 foreign key

Viewed 12593

I try to migrate my table that have a foreign keys. Every time I migrate my table it produce an error which is saying:

General error: 1215 Cannot add foreign key constraint

Here is my table migration:

Schema::create('profile_pictures', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->nullable();
    $table->binary('image')->nullable();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

And here is my model:

class ProfilePicture extends Model
{
    protected $fillable = [
        'user_id',
        'image'
    ];

    public function user()
    {
        $this->belongsTo(User::class, 'user_id', 'id');
    }
}

Here is my user table migration:

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

Update the user_id col from bigInteger to UnsignedBigInteger as you need the same datatype and length for PK and FK.

Schema::create('profile_pictures', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->binary('image')->nullable();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

I will suggest to follow convention and use foreignId() method with constrained()

Sample(from documentation):

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

You can get more details here: https://laravel.com/docs/8.x/migrations#foreign-key-constraints

According to WL#148, a foreign key column must have the same data type + the same length + the same scale as the corresponding referenced column.

I think you should use

$table->unsignedBigInteger('user_id')->nullable(); 

Instead of

$table->bigInteger('user_id')->nullable();
Related