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

akc4's avatar
Level 1

Sync hasMany relationship

I have an edit page for comments attached to a post. With the edit page I am able to edit, delete, add new comments in bulk rather than one by one.

As there is no sync for hasMany relationship, I was wondering if deleting all the relations and then re-creating them is "good" practice rather than checking the array of comments one by one and checking if it already exists or if it has been modified or deleted from the array..

$post = Post::where('id', $id)->where('user_id', Auth::user()->id)->first();

        $post->comments()->delete();

        foreach ($request->comments as $value) {
            Comment::create([
                'comment' => $value['comment'],
                'user_id' => $value['user_id'],
                'post_id' => $post->id
            ]);
        }
0 likes
2 replies

Please or to participate in this conversation.