how to insert data into many many relationship?

Viewed 84

i have a table that has four IDs of different models, they have a relationship of many to many

  public function up()
{
    Schema::create('district_group_project_users', function (Blueprint $table) {
        $table->id();
        $table->uuid('district_id');
        $table->uuid('group_id');
        $table->uuid('project_id');
        $table->uuid('user_id');
        $table->timestamps();
    });
}

now i like to save the data in the following table I used the relationship to function in each model in project.php

    public function users()
{
 return $this->belongsToMany(User::class,'district_group_project_user');
}

in other too i used same type of function and in the user controller i want to attach

        $user->project()->attach($request->district,$request->userGroup,$request->project);

it does not save, any idea how to save the following values one time

1 Answers

you can use newPivotQuery Method, witch make the query relative to the pivot table:

 $user->project()->newPivotQuery()
            ->insert(['user_id'=>$user_id,'project_id'=>$request->project,
'group_id'=>$request->userGroup,'district_id'=>$request->district])
Related