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

Shengjie's avatar

Update many-to-many pivot table

There are three tables, users, project_user, projects. In the pivot table, project_user, there are only 2 columns user_id and project_id as foreign keys associated with users and projects.

What I want to do is simply change all the project_id=1 to project_id=2 in the pivot table. Here is my code: DB::table('project_user')->where('project_id',1)->update(['project_id'=>2]);

I want to know is there any better way to do that? Any demo code is appreciated.

0 likes
1 reply
ehab.aboshehab's avatar

@shengjie In the User model you can add :

public function projects()
    {
        return $this->belongsToMany(Project::class, 'project_user');
    }

And you can use something like this :

$user->projects()->detach(1);
$user->projects()->attach(2);

Please or to participate in this conversation.