The existing ones should not be all removed. Those should only be updated or deleted.
You might want to have a look at the updateOrCreate and upsert methods.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
]);
}
@akc4 Check this. You may get some idea
https://stackoverflow.com/questions/27204485/synchronizing-a-one-to-many-relationship-in-laravel
Please or to participate in this conversation.