Search code examples
laravellaravel-9

Laravel 9 foreignId [Foreign key constraint is incorrectly formed]


I am getting an error while using foreign keys.

Products migration

Schema::create('product', function (Blueprint $table) {
    $table->id(); // Ürün adı
    $table->string('name'); //Ürün adı
    //$table->unsignedBigInteger('category_id');
    $table->foreignId('category_id')->constrained('category');
    $table->timestamps();
});

Category migration

Schema::create('category', function (Blueprint $table) {
    $table->id();
    $table->integer('main_category')->nullable();
    $table->string('name');
    $table->integer('commission');
});

Error

General error: 1005 Can't create table laravel.product (errno: 150 "Foreign key constraint is incorrectly formed")

I'am using laravel 9


Solution

  • You don't show the order in which you created the migrations but the categories table will need to exist before you create the product table.