title: New record and many to many insert
body: <p>I am working in a project where the users have a rate plan associated. When a new user is created, a valid rate plan must be specified.</p>
  
  <p>I have the following MySQL schema and Eloquent models:</p>
  
  <p><a href="https://i.stack.imgur.com/5iz6J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5iz6J.png" alt="enter image description here"></a></p>
  
  <pre><code>/**
   * User Eloquent model file ...
   *
   */
  
  public function ratePlans() {
      return $this-&gt;belongsToMany(
        'App\Models\RatePlan',
        'users_rate_plans',
        'users_id', 
        'rate_plans_id'
     );
  }
  </code></pre>
  
  <p>So, to create a new user with your selected rate plan i do:</p>
  
  <pre><code>try {
     \DB::beginTransaction();
     $model-&gt;create($data);
     $model-&gt;ratePlans()-&gt;attach($data['rate_plan'], ['active' =&gt; 1]);
     \DB::commit();
     return $model;
  } catch(\Exception $e) {
     \DB::rollback();
     return false;
  }
  </code></pre>
  
  <p>But, i am getting the next exception:</p>
  
  <blockquote>
    <p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column
    'users_id' cannot be null (SQL: insert into <code>users_rate_plans</code>
    (<code>active</code>, <code>rate_plans_id</code>, <code>users_id</code>) values (1, 43, ))</p>
  </blockquote>
  
  <p>Why te transaction didn't work ? How i can do that task ?</p>
  
  <p><strong>UPDATE 1</strong></p>
  
  <p>I changed the transaction code but, the result is the same.    </p>
  
  <pre><code>try {
     \DB::beginTransaction();
     $ratePlan = \App\Models\RatePlan::find($data['rate_plan']);
     $user-&gt;ratePlans()-&gt;attach($ratePlan, ['active' =&gt; 1]);
     $user-&gt;create($data);
     \DB::commit();
     return $user;
  } catch(\Exception $e) {
     \DB::rollback();
     die($e-&gt;getMessage());
     return false;
  }
  </code></pre>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>I changed the transaction code again and its works:</p>
  
  <pre><code>\DB::beginTransaction();
  $user = \App\Models\User::create($data);
  $ratePlan = \App\Models\RatePlan::find($data['rate_plan']);
  $user-&gt;ratePlans()-&gt;attach($ratePlan, ['active' =&gt; 1]);            \DB::commit();
  return $user;
  </code></pre>