Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Foreign key constraint is incorrectly formed - Laravel





I'm on Laravel 5.8 on a XAMPP stack.

Consider these two migrations to create two tables:

post_categories table.

Schema::create('post_categories', function (Blueprint $table) {

posts table.

Schema::create('posts', function (Blueprint $table) {


When I run php artisan migrate, I'm getting the following error:

General error: 1005 Can't create table testdb.#sql-38d8_102 (errno: 150 "Foreign key constraint is incorrectly formed").

I've tried running both:

  • php artisan migrate
  • php artisan migrate:fresh

I also tried changing the post_category_id field to a regular integer, instead of unsigned: no difference.

Also restarted the MySQL server and Apache service, didn't make a difference.

The post_categories migration runs before the posts migration. The posts table gets created, but the foreign key doesn't.

Why is this error being thrown and how do I solve it?

like image 485
rpm192 Avatar asked Dec 18 '22 18:12


1 Answers

This might be happening because you're trying to create a foreign key with an integer field to a big integer field. In your posts migration, instead of this


do this:

like image 136
Jose Henrique Felipetto Avatar answered Dec 20 '22 16:12

Jose Henrique Felipetto