title: How to save many to many relationships?
body: <p>I am creating the backoffice for a website I'm developing with Laravel4. So far so good, but I got into this error when trying to save a model (components) that has a <code>belongsToMany</code> relationship with another model (codes).</p>
  
  <p>I am getting this error:</p>
  
  <pre><code>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'component_id' cannot be null (SQL: insert into `component_codes` (`code_id`, `component_id`) values (4, ))
  </code></pre>
  
  <p>Here's my create blade template:</p>
  
  <pre><code>@foreach ($codes as $code)
      &lt;tr&gt;
          &lt;td&gt;{{ $code-&gt;id }}&lt;/td&gt;
          &lt;td&gt;{{ $code-&gt;code }}&lt;/td&gt;
          &lt;td&gt;{{ $code-&gt;packing }}&lt;/td&gt;
          &lt;td&gt;@if ($code-&gt;active == 1) &lt;span class="label label-success"&gt;Active&lt;/span&gt; @else &lt;span class="label label-secondary"&gt;Inactive&lt;/span&gt; @endif&lt;/td&gt;
          &lt;td&gt;&lt;input type="checkbox" name="code_checkbox[]" value="{{ $code-&gt;id }}" /&gt;&lt;/td&gt;
      &lt;/tr&gt;   
  @endforeach
  </code></pre>
  
  <p>And my store function:</p>
  
  <pre><code>$component            = new PackbuilderComponent;
  $component-&gt;name_en   = Input::get('name_en');
  $component-&gt;filter_id = Input::get('filter_id');
  $component-&gt;image     = $fullpath;
  $component-&gt;thumb     = $fullthumbpath;
  $component-&gt;codes()-&gt;sync(Input::get('code_checkbox'));
  $component-&gt;save();
  </code></pre>
  
  <p>I don't get it. Isn't it supposed to know the ID of the component it's creating and simply associate the "code_id" to the pivot table? Why is it asking for a "component_id" that doesn't even exist yet?</p>