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?
user_id
FK on your migration – Piazzi