Home > Software engineering >  Migration: Cannot add foreign key constraint - Laravel 9
Migration: Cannot add foreign key constraint - Laravel 9

Time:10-18

I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:

  SQLSTATE[HY000]: General error: 1005 Can't create table `bright`.`carts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `carts` add constraint `carts_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)

My migration code is as so: carts migration file

public function up()
{
    Schema::create('carts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('product_id')->unsigned();
        $table->integer('customer_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
        $table->string('quantity');

    });

}

products migration file

 public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('unit');
        $table->decimal('price', 6, 3);
        $table->string('img_url');
        $table->string('description');
        $table->integer('sold');
        $table->integer('in_stock');
        
    });
}

customers migration file

 public function up()
{
    Schema::create('customers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('phone_number');
        $table->string('address');
        $table->string('zip')->nullable();
        $table->string('email')->unique();
        $table->string('user_name')->unique();
        $table->string('password');
    });
}

Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. carts, products, customers. Ideally I want to create carts table which hold this data with the foreign keys, i..e product_id and cart_id

CodePudding user response:

Try using this structure.

$table->foreignIdFor(Product::class);
$table->foreign('product_id')->references('id')->on('products');
$table->foreignIdFor(Customer::class);
$table->foreign('customer_id')->references('id')->on('customers');

Also make sure, your products and customers migrations run before your carts migrations, and your models are imported to your migrations.

CodePudding user response:

You can use like this.

$table->unsignedBigInteger('product_id')->nullable();
$table->foreign('product_id')->references('id')->on('products');
$table->unsignedBigInteger('customer_id')->nullable();
$table->foreign('customer_id')->references('id')->on('customers');
  • Related