Fix Laravel “SQLSTATE[HY000]: Cannot add foreign key constraint” (2025)

Fix Laravel “SQLSTATE[HY000]: Cannot add foreign key constraint” (2025)

🔧 Fix “SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint” in Laravel (2025)

When running migrations in Laravel, you may face this error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint


This looks scary 😱, but it’s a very common issue and has some simple fixes. Let’s break it down.

🚨 Why Does This Error Happen?

Laravel uses MySQL (or MariaDB) under the hood. This error usually happens when:

Wrong Database Engine

MySQL supports foreign keys only in InnoDB engine, not in MyISAM.

Datatype Mismatch

Your foreign key column and the referenced column must have the same datatype.

Example: If id is unsignedBigInteger, then the foreign key must also be unsignedBigInteger.

Order of Migrations

The parent table must exist before the child table tries to reference it.

🛠 Step-by-Step Fix
✅ 1. Check Table Engine

Make sure your tables use InnoDB. In your migration, always use:

Schema::create('users', function (Blueprint $table) {
$table->id(); // unsignedBigInteger by default
$table->string('name');
$table->timestamps();
});


👉 If your table is still created with MyISAM, change the default engine in your config/database.php:

'mysql' => [
'engine' => 'InnoDB',
],

✅ 2. Match Foreign Key Datatypes

Suppose you have users and posts tables.

❌ Wrong:

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


✅ Correct:

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


Always match the datatype with the parent table’s primary key.

✅ 3. Migration Order

If posts references users, the users table must be migrated first.

Run php artisan migrate:status to check migration order.

If needed, rename migration files to fix order (example: 2025_01_01_000000_create_users_table.php should come before 2025_01_01_010000_create_posts_table.php).

✅ 4. Refresh Migrations

If you already tried multiple times and messed up, just refresh everything:

php artisan migrate:fresh --seed


👉 This drops all tables, runs migrations again, and seeds fresh data.

🎯 Pro Tips

Always use $table->id() (auto unsignedBigInteger) for primary keys.

When creating foreign keys, use $table->foreignId('user_id')->constrained()->onDelete('cascade'); – this is clean and prevents errors.

Check for typos in table names or column names.

✅ Final Words

This error looks complex but is easy to fix once you understand:

Database engine = InnoDB

Datatype must match

Migration order matters

Back