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

umefarooq's avatar

how to save only selected items using hasMany on update and remove already save items not selected.

Hi, i need help for updating one to many relationship, i am using multiple select dropdwon list and checkbox array to save information. first time save is working fine, on update if i uncheck or not selecting any old item, it should save only selected items, already save uncheck or not selected item should be deleted from database.

it is one to many relation not many to many relation. I am try to save time slots for a user in user_times table

$user->times()->saveMany($slot);

$user->times()->delete() works fine for me but its deleting all saved records for user and creates new.

0 likes
8 replies
Nash's avatar

Just detach the old entries before attaching the current + new ones? If it's nothing more than a few selections then it should be fine.

$model->relateditems()->detach();
$model->relateditems()->attach($relateditems);
Snapey's avatar

You may be falling foul of the fact that unchecked checkboxes are not returned with the form response.

So, unless you code for this, you will be able to set items but not unset them.

There are many approaches for this, the most common being a hidden form element of the same name that is placed before the checkbox

meeshka's avatar

@Snapey maybe he can pull existing entries and do a intersect of collections?

Trajce10286's avatar

What about using: $user->times()->whereNotIn('id',[Updated ID-s])->delete();

1 like
mantasja's avatar

I had the same question/problem. I sloved it by creating extra hidden input for each delete button click and saved ID of deleted value into that hidden input (name: deleted_fields[]). So in controller I just deleted all fields from deleted_fields array and updated what left :)

Please or to participate in this conversation.