title: Laravel : Many to many insertion
body: <p>I have two models, <code>User</code> and <code>Team</code>
  The relationship between them is <code>ManyToMany</code>:</p>
  
  <p>In <code>User</code>:</p>
  
  <pre><code>public function teamMembers(){
      return $this-&gt;belongsToMany('App\Team')-&gt;withPivot('id');;
  }
  </code></pre>
  
  <p>And in <code>Team</code> :</p>
  
  <pre><code>public function teamMembers(){
      return $this-&gt;belongsToMany('App\User')-&gt;withPivot('id');;
  }
  </code></pre>
  
  <p>Now i want to add users to a specific team. So the pivot table name is <code>team_user</code>. </p>
  
  <p>Now the data i want to insert to pivot table is :</p>
  
  <pre><code>array:4 [▼
    "_token" =&gt; "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh"
    "team_id" =&gt; "1"
    "members_id" =&gt; array:3 [▼
      0 =&gt; "2"
      1 =&gt; "3"
      2 =&gt; "4"
    ]
    "status" =&gt; "1"
  ]
  </code></pre>
  
  <p>What i am doing in my controller :</p>
  
  <pre><code>$team_id = $request-&gt;get("team_id");
  $team = \App\Team::findOrFail($team_id);
  foreach ($request-&gt;get('members_id') as $key =&gt; $value) {
      $team-&gt;teamMembers()-&gt;attach($team);
      $team-&gt;save();
  }
  </code></pre>
  
  <p>But it only inserts one record, I mean the <code>team_id</code> and the first <code>member_id</code>.
  I want it to create one record per member from the <code>members_id</code> array. How am i gonna do that ?</p>