Search code examples
laraveleloquent-relationship

Laravel foreign key constraint is incorrectly formed (errno 150)


can someone tell me why do I get a foreign key is incorrectly formed?

Here is part of the code:

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('title');
            $table->text('content');
            $table->string('featured');
            $table->string('slug');
            $table->foreignId('category_id')->constrained()->onDelete('cascade');

            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }

Here is the categories table:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }

Note

It does not drop this error for 'user_id' foreign key just for categories.

FIX FOR THIS ISSUE

just change date on your database/migrations - migration for example if you want your categories to be created before posts table do this change:

2020_08_06_172006_create_posts_table.php 2020_08_09_172006_create_categories_table.php

change date on categories migration from 2020_08_09 to for example 2020_07_09


Solution

  • I'm guessing your table posts is created before categories
    Therefore, you cannot constraint posts.category_id to the categories.id table.

    In order to fix the issue you should create the table categories before creating the table posts