Fixing Laravel SQLSTATE[HY000]: Cannot Add Foreign Key Constraint (Errors 1215 & 3780)
When running php artisan migrate, few errors halt database setup faster than a failed foreign key constraint. Depending on your MySQL or MariaDB version, your terminal will throw one of two fatal exceptions:
MySQL 5.7 / MariaDB (Error 1215):
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `orders` add constraint `orders_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
MySQL 8.0+ (Error 3780):
SQLSTATE[HY000]: General error: 3780 Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'orders_user_id_foreign' are incompatible.
Both errors mean the same thing: MySQL rejected your relationship because the child column and parent column do not strictly match in data type, sign, charset, or table availability.
Quick Diagnostic Reference
Match your migration setup to the exact cause below:
| Symptom / Setup | Root Cause | Jump To |
|---|---|---|
Error 3780 on a brand new migration |
Signed integer / bigInteger referencing an unsignedBigInteger (id()) |
Step 1 |
| Child migration runs before parent table exists | Migration file timestamp ordering issue | Step 2 |
onDelete('set null') throws Error 1215 |
Foreign key column is missing ->nullable() |
Step 3 |
| String / UUID foreign key fails across tables | Character set (utf8mb4) or collation mismatch |
Step 4 |
| Legacy database tables rejecting constraints | Parent or child table uses MyISAM instead of InnoDB |
Step 5 |
Step 1: Fix Signed vs. Unsigned Column Type Mismatches (Error 3780)
Since Laravel 5.8+, calling $table->id() on a parent table creates an UNSIGNED BIGINT auto-incrementing primary key (unsignedBigInteger).
If you define your foreign key on the child table using $table->bigInteger('user_id') or $table->integer('user_id'), MySQL rejects the constraint because a signed integer cannot reference an unsigned big integer.
The Broken Migration:
Schema::create('orders', function (Blueprint $table) {
$table->id();
// BROKEN: bigInteger is signed by default, while users.id is unsigned
$table->bigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
The Fix (Modern Laravel foreignId Syntax):
Replace manual two-line definitions with foreignId()->constrained(), which automatically matches the exact UNSIGNED BIGINT specification of $table->id():
Schema::create('orders', function (Blueprint $table) {
$table->id();
// FIXED: Automatically creates an UNSIGNED BIGINT and binds to users.id
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->timestamps();
});
If you are referencing a legacy parent table that used $table->increments('id') (which creates an UNSIGNED INT instead of BIGINT), you must match it with unsignedInteger:
$table->unsignedInteger('legacy_category_id');
$table->foreign('legacy_category_id')->references('id')->on('legacy_categories');
Step 2: Fix Migration Timestamp Execution Order
Laravel executes migrations strictly in alphabetical order based on their filename timestamps. If 2026_11_07_000001_create_orders_table.php runs before 2026_11_07_000005_create_customers_table.php, MySQL cannot bind a foreign key to a customers table that does not exist yet.
Check your execution order by running:
php artisan migrate:status
The Fix:
Rename the child migration file so its timestamp occurs after the parent table’s migration file:
# Move the child table timestamp after the parent table
mv database/migrations/2026_11_07_000001_create_orders_table.php \
database/migrations/2026_11_07_000006_create_orders_table.php
Then reset and re-run your migrations cleanly:
php artisan migrate:fresh
Step 3: Add nullable() Before nullOnDelete()
A classic trap that triggers 1215 Cannot add foreign key constraint is instructing MySQL to SET NULL when a parent record is deleted, without allowing the child column to hold NULL values.
The Broken Migration:
// BROKEN: Column is NOT NULL, so MySQL rejects ON DELETE SET NULL
$table->foreignId('author_id')->constrained('users')->nullOnDelete();
The Fix:
In Laravel’s Schema builder, column modifiers like ->nullable() must be chained before calling ->constrained():
// FIXED: nullable() is applied to the column before the constraint is built
$table->foreignId('author_id')
->nullable()
->constrained('users')
->nullOnDelete();
Step 4: Inspect Hidden MySQL Foreign Key Errors (SHOW ENGINE INNODB STATUS)
When MySQL throws a generic 1215 error, it hides the exact internal reason from PDO. You can force MySQL to reveal the exact failure detail by running this query inside php artisan tinker or your database client right after the migration fails:
SHOW ENGINE INNODB STATUS;
Look under the LATEST FOREIGN KEY ERROR section in the output. Common hidden culprits include:
- Charset & Collation Mismatch (String / UUID Foreign Keys):
Ifusers.uuidusesutf8mb4_unicode_ciandorders.user_uuidusesutf8mb4_general_ci(often caused by creating tables at different times after changingconfig/database.php), MySQL refuses to link them. Explicitly unify them in your migration:$table->uuid('user_uuid')->charset('utf8mb4')->collation('utf8mb4_unicode_ci'); - Missing Index on Referenced Column:
If you are referencing a non-primary column (e.g.,references('sku')->on('products')), the parentskucolumn must have a->unique()or->index()modifier.
Step 5: Verify Both Tables Use the InnoDB Storage Engine
MySQL’s MyISAM storage engine does not support foreign key constraints. If you are working on an older database or a shared hosting server that defaults to MyISAM, adding a foreign key will either fail with Error 1215 or silently ignore the constraint.
Verify your table engines in MySQL:
SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE();
To enforce InnoDB across all migrations in Laravel, ensure engine is explicitly set in config/database.php:
'mysql' => [
'driver' => 'mysql',
// ...
'engine' => 'InnoDB',
],
Pre-Migration Verification Checklist
- Use
foreignId('model_id')->constrained()whenever referencing a standard$table->id()column. - Place
->nullable()before->constrained()whenever using->nullOnDelete(). - Check migration filenames to verify parent tables are created before child tables.
- Ensure referenced non-ID columns have a
->unique()index on the parent table.