Foreign Key Laravel 8 foreignId + constrained – Cannot add or update a child row: a foreign key constraint fails

I have ‘categories_blogs’ and ‘blogs’ migration.

I’m using new foreignId, constrained with bigint, I get this follow error when add a row in ‘blogs’ table:

Cannot add or update a child row: a foreign key constraint fails (test.blogs, CONSTRAINT blogs_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories_blog (id))

    Schema::dropIfExists('categories_blogs');

    Schema::create('categories_blogs', function (Blueprint $table) {
        $table->id();
        $table->string('category_name');
        $table->timestamps();
    });

   Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('category_id')->constrained('categories_blog');
            $table->string('slug');
            $table->string('title');
            $table->timestamps();
  });

Instead without bigint and old foreign key way, works fine:

Schema::dropIfExists('categories_blogs');

Schema::create('categories_blogs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('category_name');
    $table->timestamps();
});

Schema::create('blogs', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('blogs')->onDelete('cascade');
    $table->string('slug');
    $table->string('title');
    $table->string('description');
    $table->longtext('content');
    $table->timestamps();
});

How can I fix it? thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

According to the documentation, constrained() method will use conventions to determine the table name :

$table->foreignId('category_id')->constrained('categories_blogs');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x