Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iMsIdZz's avatar

Error SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Here is my create post form

    {!! Form::open(['route' => 'news.store', 'files'=>true])   !!}
   <!-- {!! Form::hidden('User_id', Auth::user()->id) !!} -->
<div class="container-fluid">
<div class="row">
    <div class="col-md-12">
        <form role="form">
            <div class="form-group">
                 
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title', null, ['class'=>'form-control']) !!}
            </div>
            <div class="form-group">
                 
                 {!! Form::label('body', 'body:') !!}
        {!! Form::textarea('body', null, ['class'=>'ckeditor', 'rows'=>5] ) !!}
            </div>
            <div class="form-group">
        {!! Form::label('image', 'Choose an Image') !!}
        {!! Form::file('image') !!}
        </div>
        <div class="form-group">
                 {!! Form::label('tags', 'tags:') !!}
        {!! Form::select('tags[]', $tags, null, ['class'=>'form-control', 'multiple']) !!}
            </div>
            <div class="checkbox">
                 
                <label>
                    <input type="checkbox" /> I Accept
                </label>
             </div> 
            <div class="form-group">
        {!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}

here is my controller

    public function store(Request $request)
     {   
    $this->validate($request, [
        'title' => 'required|max:255',
        'body' => 'required|max:100000',
        'image' => 'image',
    ]);

    
    $news = new news;
    $news->tags()->attach($request->input('tags'));
    $news->title = $request->title;
    $news->body = $request->body;
    if($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        
        $name = $timestamp. '-' .$file->getClientOriginalName();
        
        $news->image = $name;

        $file->move(public_path().'/../public_html/news_image/', $name);

        $thumb = Image::make(public_path().'/../public_html/news_image/' . $name)->resize(484, 300)-        >save(public_path().'/../public_html/news_image/thumb/thumb' . $name, 50);
    }

    $news->save();

    return redirect()->route('news.index');
        }

this is my database migration

    <?php

    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

class CreateNewsTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
     Schema::create('news', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('body');
        $table->string('image')->default('defaulttagimage.jpg');
        $table->timestamps();
        $table->foreign( 'user_id' )->references( 'id' )->on( 'users' );
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('news');
    }
}

Getting error when i create new post with tags
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (latest.news_tag, CONSTRAINT news_tag_news_id_foreign FOREIGN KEY (news_id) REFERENCES news (id) ON DELETE CASCADE) (SQL: insert into news_tag (news_id, tag_id) values (, 3), (, 4))

0 likes
12 replies
iMsIdZz's avatar

if i know why i am getting error than why i post for help

d3xt3r's avatar

Hands on is good, but some theory is nice. The error is there, shouting that please don't do this. It is advisable to have some debugging skills along side the programming skills. No offence.

So if you wan't help in real terms and not just the corrected piece of code

https://www.google.co.in/search?q=Cannot+add+or+update+a+child+row%3A+a+foreign+key+constraint+fails&oq=Cannot+add+or+update+a+child+row%3A+a+foreign+key+constraint+fails&aqs=chrome..69i57j69i60l2.1150j0j7&sourceid=chrome&ie=UTF-8

iMsIdZz's avatar

Sorry premsaurav this is not a sollution i already searched on google i found so much but still have error if you can fix this than please

EventFellows's avatar

From looking at your code it seems like here is problem

Your News Tables requires a 'user_id' that is the base for your foreign key constraint:

$table->integer('user_id')->unsigned();

But on your store method you are not passing any user_id.

Just try to hardcode that in to see if that solves your issue like so:

$news->user_id = 1; // choose a user id that exists on your users table.
2 likes
d3xt3r's avatar

@iMsIdZz @EventFellows That is the reason why paying attention to exceptions is equally important. It clearly says which constraint is being violated.

Anyway, you need to store the news first (which again would fail if user_id is not passed) and then you can attach the tags.

stevenobird's avatar
Level 11

Nobody noticed the missing news_id in the insert statement?

insert into news_tag (news_id, tag_id) values (, 3), (, 4)

Instead of

$news = new News;

you should create it directly to get a news_id from the database (which is needed for the related news_tags table), otherwise your $news->news_id will be empty (which is the case in this one).

This way here might one right way:

// first CREATE the news (not just an empty instance, but a full model with own unique id)
$news = News::create([
    'title' => $request['title'],   // $request->title also works?
    'body' => $request['body'], // $request->body also works?
    'user_id' => Auth::user()->id   // there might be a better solution, but this works 100%
]);
// since image has a default, you should be able leave it out at creation...I'm not sure.

// now your news has an ID and you can use the relationships...
$news->tags()->attach($request->input('tags'));

// route to anywhere...
return redirect()->route('news.index');
stevenobird's avatar

@premsaurav you talked about a missing user_id attached to the news (which will also cause problems when saving the news), but the first problem is the missing news_id, because the news is not yet created in the database and the attachment to the news_tag table fails because of that since the foreign key depends on that news_id.

d3xt3r's avatar

Want to enter into a fight :P there you go

Anyway, you need to store the news first (which again would fail if user_id is not passed) and then you can attach the tags.

1 like
stevenobird's avatar

Oh man sorry - I should learn to read details... :D

Yeh, you are 100% right - I think I was just missing some code in your answer.

Please or to participate in this conversation.