Posts Learn Snippets Categories Tags About
/

How to Prevent Foreign Key Error in Laravel Migration

Learn how to prevent foreign key error caused by unmatched datatype.

Created on Jul 02, 2021

6 views

When defining a foreign key in Laravel, It's important to ensure that the foreign column key has the same data type as the primary key it's referencing to and the column set to be unsigned. This is to ensure that the foreign key is compatible with the primary key.

So instead of "bigInteger()", you can use "unsignedBigInteger()" or "bigInteger()->unsigned()".
Schema::create('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id')->index();

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

On the user table, it will be like the usual definition,
Schema::create('users', function (Blueprint $table) {
    $table->id();
});

Do note the when inspecting the"id()" helper the content is just "bigIncrements()" so don't get confused by it.
return $this->bigIncrements($column);

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.