title: Laravel 5: syncing an extra field via pivot
body: <p>User model:</p>
  
  <pre><code>public function positions()
  {
   return $this-&gt;belongsToMany('App\Position')-&gt;withPivot('company_id')-&gt;withTimestamps();
  
  }
  </code></pre>
  
  <p>Positions model:</p>
  
  <pre><code>public function users()
  {
   return $this-&gt;belongsToMany('App\User')-&gt;withPivot('company_id')-&gt;withTimestamps();
  }
  </code></pre>
  
  <p>On form submission I have two arrays:</p>
  
  <pre><code>$allPositionIds
  array:3 [
  0 =&gt; 98
  1 =&gt; 99
  2 =&gt; 100
  ]
  
  
  $allCompanyIds
  array:3 [
  0 =&gt; 129
  1 =&gt; 130
  2 =&gt; 131
  ]
  </code></pre>
  
  <p>Using </p>
  
  <pre><code>$user-&gt;positions()-&gt;sync($allPositionIds);
  </code></pre>
  
  <p>that syncs the position_user table as expected with the user and corresponding position ids. </p>
  
  <p>However I can't work out how to populate the extra field ('company_id')</p>
  
  <p>This is kind of what I would expect to work:</p>
  
  <pre><code>$user-&gt;positions()-&gt;sync([$allPositionIds =&gt; ['company_id' =&gt; $allCompanyIds]], false);
  </code></pre>
  
  <p>I have read the <a href="http://laravel.com/docs/eloquent" rel="nofollow noreferrer">manual</a> but I am just not seeing how to handle these arrays as the examples in the manual seem to relate to a situation where the extra field to be populated is not an array of multiple items:</p>
  
  <pre><code>$user-&gt;roles()-&gt;sync(array(1 =&gt; array('expires' =&gt; true)));
  </code></pre>
  
  <p>I have tried using this <a href="https://stackoverflow.com/questions/27230672/laravel-sync-how-to-sync-an-array-and-also-pass-additional-pivot-fields">answer</a></p>
  
  <p>to combine the two arrays:</p>
  
  <pre><code>$syncData = array_combine($allPositionIds,$allCompanyIds);
  </code></pre>
  
  <p>and get $syncData of :</p>
  
  <pre><code>array:3 [
  98 =&gt; 129
  99 =&gt; 130
  100 =&gt; 131
  ]
  </code></pre>
  
  <p>Which maps accordingly to position id array and company id array but if I try</p>
  
  <pre><code>user-&gt;positions()-&gt;sync($syncData);
  </code></pre>
  
  <p>I get a <code>"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" - I believe it is trying to add in the company_id as another position_user.position_id but then it errors out as that doesn't exist in the positions table.</code></p>
  
  <p>Whatever I am trying at the moment my <code>company_id</code> field is still not being updated/populated.</p>
  
  <p>What am I doing wrong and how do I update that field?</p>