-1

category_id foreign key is not taken while migration and throws some error.

Here are my migration files:

create_categories_table :

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

create_products_table:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->integer('price')->nullable();
            $table->integer('category_id');
            $table->text('description')->nullable();
            $table->integer('quantity')->default(0);
            $table->string('image')->nullable();
            $table->json('gallery')->nullable();
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
            $table->timestamps();
        });
    }

I am getting this error in my console.

Illuminate\Database\QueryException

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

  at C:\eshop\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

  1   C:\eshop\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `eshop`.`products` (errno: 150 "Foreign key constraint is incorrectly formed")")

  2   C:\eshop\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOStatement::execute()
Tanjib Rubyat
  • 27
  • 2
  • 7

1 Answers1

0
$table->integer('category_id');

must be of type

$table->unsignedBigInteger('category_id');

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

You will probably also have to change

$table->increments('id');

to

$table->bigIncrements('id');
//or
$table->id();
Aless55
  • 2,652
  • 2
  • 15
  • 26