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

Neeraj1005's avatar

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`study6_cms`.`post_tag`, CONSTRAINT `post_tag_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)) (SQL: insert into `po

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`study6_cms`.`post_tag`, CONSTRAINT `post_tag_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)) (SQL: insert into `post_tag` (`post_id`, `tag_id`) values (3, 3))

In my localhost post store with tag is properly working. But in server it throw an errror can anyone please tells me what I did wrong...? StoreMethod

   public function store(PostStoreRequest $request)
    {
        
        $input = $request->validated();

        $posts = auth()->user()->posts()->create($input);

        if (request('tags') != '') {
            $tags = explode(',', request('tags'));
            foreach ($tags as $tag_name) {
                $tag = Tag::firstOrCreate(['name' => $tag_name]);
            }
            $posts->tags()->attach($tag);
        }
        
        return redirect(route('posts.index'))->withMessage('post 😊 created successfully');
    }

blade file

 <input type="text" name="tags" class="form-control"
         value="{{ old('tags') }}" />
     @error('tags')
      <small class="form-text text-red">{{ $message }}</small>
     @enderror

0 likes
10 replies
bugsysha's avatar

It is complaining that wrong reference has been provided for the post ID. What are the values for $posts and $tag variables?

MichalOravec's avatar

I would change it to this

public function store(PostStoreRequest $request)
{
    $post = auth()->user()->posts()->create($request->except('tags'));

    if ($request->tags) {
        $ids = [];

        foreach (($tags = explode(',', $request->tags)) as $tag) {
            $ids[] = Tag::firstOrCreate(['name' => $tag]);
        }

        $post->tags()->attach($ids);
    }

    $request->session()->flash('message', 'post 😊 created successfully');

    return redirect()->route('posts.index');
}
1 like
Tray2's avatar

The error means that you are trying to insert a tag with a post_id that doesn't exist as an id in the posts table.

I'm in the process of writing a guide about SQL error message in Laravel and this is the chapter on this error.

The refusal to add or update AKA ERROR 1452 (23000): Cannot add or update a child row:

This error is a distant cousin to the previous error. In this case the foriegn key is preventing us from inserting a record in the books table with an author_id that does not exist in the authors table.

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 
`laraveldb`.`books`, CONSTRAINT `books_author_id_foreign` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE)

This error migth not be that common in Laravel but I think it's good to know what causes it and how to solve it.

Take this piece of php code in the store method of our Book Controller.

$book = new Book();
$book->title = 'The Wizards First Rule';
$book->author_id = 2;
$book->save();

So the error above tells us that a foreign key constraint fails. That tells us that there is something with our constraint. If we take a look att our authors table and it's contents we will see this.

mysql> select * from authors;
+----+---------------+------------+------------+
| id | name          | created_at | updated_at |
+----+---------------+------------+------------+
|  1 | Robert Jordan | NULL       | NULL       |
+----+---------------+------------+------------+
1 row in set (0.00 sec)

Now since we are using a foreign key constraint it means that our foreign key must exist as a primary key in our authors table. To solve this issue we need either to change the author_id in our insert or create a new author.

So if we create the author first

$author = Author::create(['Terry Goodkind']);

Then we can create the book.

$book = new Book();
$book->title = 'The Wizards First Rule';
$book->author_id = $author->id;
$book->save();

This error is best avoided by using the exists validation rule before trying to insert a new record.

'author_id' => 'required|exists:authors,id'
2 likes
munazzil's avatar
munazzil
Best Answer
Level 13

Check your migration order that may caused this problem.

2 likes
Tray2's avatar

This have nothing to do with migrations to do, That is another error message.

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

1 like
Neeraj1005's avatar

@munazzil @tray2 In this case, this was a database problem in my server....because in my localhost the code was running but in server it sends some error. so I dorp the tables and reinsert with migration and code runs...

1 like
Tray2's avatar

Of course it does since it resets the counters for the primary keys.

AlecSquire's avatar

Had a simmilar issue arise thought id share my solution. Instead of running
php artisan migrate:refresh
Which will recreate the database from scratch, try
php artisan migrate:fresh --seed instead.
This will drop all tables in the database and re run the migrate command, preventing the foreign key constraint.

Please or to participate in this conversation.