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

cooperino's avatar

Update specific column on pivot table from given array of ids

I have 3 tables: users, lists and user_to_list

I am given array of ids of lists. in the user_to_list table this id is referred to as list_id

I need to update all the rows in specific column to value 1 in the user_to_list table for a user given the array of list_ids

What is the correct query?

I tried a few variations that start with

$user->userToList->where.. // but got stuck here (failed)

(The relationships are set correctly including the userToList)

0 likes
5 replies
MichalOravec's avatar
Level 75

Like this?

DB::table('user_to_list')->where('user_id', $user->id)->whereIn('list_id', $listOfIds)->update([
    'column' => 1
]);
1 like
cooperino's avatar

@MichalOravec I will try and update you if it's working. I keep getting confused as to when I should use eloquent and when query builder.

Was there a way to do that how I tried? via the $user object? something like:

$user->userToList->where(//for each given list_id, the user id is the $user->id)->update...

cooperino's avatar

@MichalOravec thank you

Btw, do I need to prevent unnecessary data search so only update the rows where the value is a specific one (for example, change the column value to 1 only if it's not already 1 and don't go over all the rest, maybe by adding ->where('column', '!=' , 1)

Please or to participate in this conversation.