I user below tutorial for laravel categories :

Laravel categories with dynamic deep paths

I use below code same tutorial for migration :

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->integer('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }

but I have below error :

SQLSTATE[HY000]: General error: 1005 Can't create table 'xxx'.'#sql-453_147' (errno: 150 "Foreign key constraint is incorrectly formed")
(SQL: alter table 'categories' add constraint 'categories_parent_id_foreign' foreign key ('parent_id') references 'categories' ('id') on delete cascade on update cascade)

Thanks for help

2 Answers

1
DAVID AJAYI On Best Solutions

When creating a new table in Laravel. A migration will be generated like:

$table->bigIncrements('id');

Instead of (in older Laravel versions):

$table->increments('id');

When using bigIncrements the foreign key expects a bigInteger instead of an integer. So your code will look like this:

public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->bigInteger('parent_id')->unsigned()->default(0);
            $table->timestamps();
        });

        Schema::table('categories', function (Blueprint $table) {
            $table->foreign('parent_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
        });

    }
0
nakov On

The problem is because of the difference of the column types. So unlike the tutorial you are using bigIncrements which means big integer for the ID and using the default integer for the parent_id. Try changing the id to this:

$table->increments('id');

or your parent_id to this:

$table->bigInteger('parent_id')->unsigned()->default(0);