Home / Snippets / How to Prevent Foreign Key Error in Laravel Migration
How to Prevent Foreign Key Error in Laravel Migration cover

How to Prevent Foreign Key Error in Laravel Migration

333

3 years ago

0 comments

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);
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this