title: Laravel 5.8 many to many relation using custom column names for pivot table
body: <p>I have two tables <code>user_details</code> and <code>location</code> as below:</p>
  
  <pre><code>user_details
      user_id (INTEGER PRIMARY KEY)
      ......
  
  location
      id (INTEGER UNSIGNED PRIMARY KEY)
      ......
  </code></pre>
  
  <p>These two tables are related to one another by many to may relationship. Now I am using a pivot table <code>location_user_details</code> as shown below</p>
  
  <pre><code>location_user_details
      id (INTEGER UNSIGNED PRIMARY KEY),
      user_id (INTEGER FOREIGN KEY REFERENCES use_details.user_id)
      location_id (INTEGER FOREIGN KEY REFERENCES location.id)
      type (VARCHAR)
  </code></pre>
  
  <p>The relation code for model <code>UserDetails</code> is as below:</p>
  
  <pre><code>class UserDetails extends Model
  {
      protected $primaryKey = 'user_id';
      ........
      public function location(){
          return $this-&gt;belongsToMany(Location::class, 'location_user_details', 'user_id', 'id')-&gt;withPivot('type');
      }
  }
  </code></pre>
  
  <p>The relation code for model <code>Location</code> is as below:</p>
  
  <pre><code>class Location extends Model
  {
      ......
      public function userDetails(){
          return $this-&gt;belongsToMany(UserDetails::class, 'location_user_details', 'id', 'user_id')-&gt;withPivot('type');
      }
  }
  </code></pre>
  
  <p>Now in my controller, I am creating the relation after saving both <code>UserDetails</code> and <code>Location</code> object by the following code:</p>
  
  <pre><code>$userDetails-&gt;location()-&gt;attach($location-&gt;id, ['type'=&gt;'HEADQUARTER']);
  </code></pre>
  
  <p>When the code reaches this line of execution, I get the following exception:</p>
  
  <blockquote>
    <p>SQLSTATE[HY000]: General error: 1364 Field 'location_id' doesn't have a default value (SQL: insert into <code>location_user_details</code> (<code>id</code>, <code>type</code>, <code>user_id</code>) values (1, HEADQUARTER, 0))</p>
  </blockquote>
  
  <p>I want to point out to two things that are happening.</p>
  
  <ol>
  <li>The location field is not getting into the query to insert data.</li>
  <li>The <code>user_id</code> value is <code>0</code> which should be greater than <code>0</code> as the data is getting inserted into the <code>user_details</code> table.</li>
  </ol>
  
  <p>Now let me mention here that when I go to the database to look up for data in <code>location</code> and <code>user_details</code> table, I find all the data has been inserted.</p>
  
  <p>Now my question is what has possible gone wrong with this code?</p>