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

DevinSephone's avatar

Updating multiple many to many relationships

I am wondering if there is a best practice when it comes to updating the pivot table for a many to many relationship. I currently have the following code which updates each pivot table record individually, but wonder if there is a better way to do this?

foreach( $job->codes as $code ) {
    $job->codes()->updateExistingPivot(
        $code->id,
        [
            'approved' => 1
        ]
    );
}
0 likes
4 replies
DevinSephone's avatar

Thanks for the response @Jawelo. From what I read, sync() is used to construct new many to many relations, not update existing ones. It also requires a list of IDs to sync the relationship with, which I don't have without doing some sort of foreach over the returned collection. I will see if I can get the list of IDs out of that and see if sync() will work for me.

cleanse's avatar

Pretty sure your original idea is the way to go.

mironmg's avatar

why not using the DB facade? May be easier.

DB::table('code_job')->where('job_id', $job_id)->update['approved',1]);
1 like

Please or to participate in this conversation.