How to fix error on Foreign key constraint incorrectly formed in migrating a table in Laravel

 

How to fix error on Foreign key constraint incorrectly formed in migrating a table in Laravel

The "Foreign key constraint incorrectly formed" error in Laravel usually occurs when the data types of the referencing and referenced columns in the foreign key are mismatched. To fix this error, you need to ensure that the data types of the columns match exactly.

Here are the steps to fix this error:

  1. Verify the data types of the referencing and referenced columns.
  2. If the data types are different, update the referencing column to match the data type of the referenced column.
  3. Run the migrations again.
Here is an example of updating the referencing column in a migration file:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddForeignKeyToOrdersTable extends Migration
{
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id')->change();
            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });
    }
}

 
In this example, the user_id column in the orders table is updated to an unsigned big integer data type to match the id column in the users table. The change method is used to update the data type, and the onDelete method sets the foreign key to cascade on delete.
Previous Post Next Post

Contact Form