title: Laravel one to Many Relationship, Integrity Constraint Violation error
body: <p>I am trying to save one to many relation to database but I am getting Integrity Constraint Violation error.</p>
  
  <p>When I use id as primary key the data gets saved successfully. But when I use custom primary key, then I get integrity constrain error.</p>
  
  <p>My database structure is like Student can study in many institutes and institute can have many courses. The error is while saving the courses.
  The error is as follows </p>
  
  <pre><code>Integrity constraint violation: 1048 Column 'institute_id' cannot be null (SQL: insert into `courses` (`institute_id`, `course_level`, `course_ ▶"
  </code></pre>
  
  <p>My code to save the data is as follows.</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>$instituteDetails = new Institute();
  $instituteDetails-&gt;institute_name = $request-&gt;input("instituteName");
  $instituteDetails-&gt;institute_location = $request-&gt;input("instituteLocation");
  $instituteDetails-&gt;institute_phone1 = $request-&gt;input("institutePhone1");
  $instituteDetails-&gt;institute_phone2 = $request-&gt;input("institutePhone2");
  $instituteDetails-&gt;institute_email = $request-&gt;input("instituteEmail");
  
  $courseDetails = new Course();
  $courseDetails-&gt;course_level = $request-&gt;input("courseLevel");
  $courseDetails-&gt;course_name = $request-&gt;input("courseName");
  $courseDetails-&gt;course_fee = $request-&gt;input("courseFee");
  $courseDetails-&gt;course_concession_fee = $request-&gt;input("courseConcessionFee");
  $courseDetails-&gt;course_duration = $request-&gt;input("courseDuration");
  $courseDetails-&gt;course_commencement_date = $request-&gt;input("courseCommencementDate");
  
  //Save institute details first
  $studentDetail-&gt;instituteDetails()-&gt;save($instituteDetails);
  
  //Then save course details
  $instituteDetails-&gt;courses()-&gt;save($courseDetails);
  </code></pre>
  
  <p>My model is as follows:-</p>
  
  <pre class="lang-php prettyprint-override"><code>protected $primaryKey = 'institute_id';
  
  public function student(){
      return $this-&gt;belongsTo("App\Model\Student");
  }
  
  public function courses(){
      return $this-&gt;hasMany('App\Model\Course', 'institute_id', 'institute_id');
  }
  </code></pre>
  
  <p>My course model is </p>
  
  <pre class="lang-php prettyprint-override"><code>class Course extends Model
  {
      //
  
      public function institute(){
          return $this-&gt;belongsTo("App\Model\Institute");
      }
  
  }
  </code></pre>
  
  <p>I don't think making foreign key null is a good idea. </p>