4
votes

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) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('slug');
  $table->string('status');
  $table->timestamps();
});

posts table.

Schema::create('posts', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('name');
  $table->string('slug');
  $table->mediumText('description');
  $table->integer('views');
  $table->integer('post_category_id')->unsigned();
  $table->integer('user_id')->unsigned();
  $table->timestamps();

  $table->foreign('post_category_id')->references('id')->on('post_categories');
});

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?

3
Check order of your migrations. In this case 'post_categories' should go before 'posts'... Finally try to add foreign key in next migration, while keeping, referenced id types identical .... - Bart
My comment has nothing to do with your problem, but you forgot to references the user_id FK on your migration - Piazzi
@LucasPiazzi, Yes I've already added it, thanks. - rpm192

3 Answers

11
votes

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

$table->integer('post_category_id')->unsigned();

do this:

$table->bigInteger('post_category_id')->unsigned();
0
votes

Instead of this:

$table->integer('post_category_id')->unsigned();

Try this:

$table->unsignedBigInteger('post_category_id');
0
votes

I had the same error where I wanted to link two tables, users tables and deposits tables. I tried many options but they didn't work. However, this is what worked for me on create deposits migration:

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