Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key constraint is incorrectly formed - Laravel

Tags:

php

mysql

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) {
  $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?

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

rpm192


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

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

do this:

$table->bigInteger('post_category_id')->unsigned();
like image 136
Jose Henrique Felipetto Avatar answered Dec 20 '22 16:12

Jose Henrique Felipetto