Posts Learn Components Snippets Categories Tags Tools 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

293 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);

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)