Hello can you help me i am getting an error in my foreign code and i can’t solve it [duplicate]

  database, laravel, mysql, php

I want to combine category_id in articles table with id in categories table

First Table

      Schema::create('articles', function (Blueprint $table) {

            $table->bigIncrements('id');
            $table->unsignedBigInteger('category_id');
            $table->string('title');
            $table->string('image');
            $table->longText('content');
            $table->string('slug');
            $table->integer('hit')->default(0);
            $table->timestamps();

            $table->foreign('category_id')->references('id')->on('categories');
            


        });

Second Table

 
Schema::create('categories', function (Blueprint $table) {

        $table->id(); 
        $table->string('name');
        $table->string('slug');
        $table->string('status')->default(1);
        $table->timestamps();
    });

I’ve shared the error I got below, please help, I can’t continue with my project, I’m stuck here

>SQLSTATE[HY000]: General error: 1005 Can't create table `ilkblog`.`articles` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `articles` add constraint `articles_category_id_foreign` foreign key (`category_id`) references `categories` (`id`))

  at Y:GitHubProjectsBlog_ProjesivendorlaravelframeworksrcIlluminateDatabaseConnection.php:703      
    699▕         // If an exception occurs when attempting to run a query, we'll format the error
    700▕         // message to include the bindings with SQL, which will make this exception a
    701▕         // lot more helpful to the developer instead of just the database's errors.
    702▕         catch (Exception $e) {
  ➜ 703▕             throw new QueryException(
    704▕                 $query, $this->prepareBindings($bindings), $e
    705▕             );
    706▕         }
    707▕     }

  1   Y:GitHubProjectsBlog_ProjesivendorlaravelframeworksrcIlluminateDatabaseConnection.php:492
      PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `ilkblog`.`articles` (errno: 150 "Foreign key constraint is incorrectly formed")")

  2   Y:GitHubProjectsBlog_ProjesivendorlaravelframeworksrcIlluminateDatabaseConnection.php:492     
      PDOStatement::execute()

Source: Laravel

Leave a Reply