title: How to fix laravel eloquent many to many relation insertion error on wrong table
body: <p>I have a model class with the name <code>CourseSession</code> and it's table is <code>course_session</code>, and I have another model named <code>Student</code> and it's table is <code>student</code> and every session has many students and also every student could be in many sessions. So I have created a third table named <code>student_session</code> with <code>student_id</code>, <code>session_id</code>, <code>presence</code> and laravels timestamp columns.</p>
  
  <p>Creating a session needs to have a list of students and I get them from <code>$request</code> like this:  </p>
  
  <pre class="lang-php prettyprint-override"><code>$validatedData = $request-&gt;validate([
      'students' =&gt; 'required',
  ]);
  </code></pre>
  
  <p><code>students</code> is array of students id!  </p>
  
  <p>this is my <code>CourseSession</code> model:  </p>
  
  <pre class="lang-php prettyprint-override"><code>class CourseSession extends Model
  {
      protected $table = 'course_sessions';
      protected $guarded = [];
  
      public function course()
      {
          return $this-&gt;belongsTo('App\Course');
      }
  
      public function students()
      {
          return $this-&gt;belongsToMany('App\Student', 'student_session','session_id', 'student_id');
      }
  }
  </code></pre>
  
  <p>and this is my student model:  </p>
  
  <pre class="lang-php prettyprint-override"><code>class Student extends Model
  {
      protected $guarded = [];
  
      public function courses()
      {
          return $this-&gt;belongsToMany('App\Course');
      }
  
      public function exams()
      {
          return $this-&gt;belongsToMany('App\Exam');
      }
  
      public function sessions()
      {
          return $this-&gt;belongsToMany('App\CourseSession', 'student_session', 'student_id', 'session_id');
      }
  }
  </code></pre>
  
  <p>I create a session like this:  </p>
  
  <pre class="lang-php prettyprint-override"><code>$session = new CourseSession();
  $session-&gt;course_id = $course-&gt;id;
  $session-&gt;save();
  </code></pre>
  
  <p>and I save students this way:  </p>
  
  <pre class="lang-php prettyprint-override"><code>$sessions = $session-&gt;students()-&gt;create(['session_id' =&gt; $session-&gt;id, 'student_id' =&gt; 1, 'presence' =&gt; 1]);
  </code></pre>
  
  <p>but I get this error:  </p>
  
  <pre><code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'session_id' in 'field list' (SQL: insert into `students` (`session_id`, `student_id`, `presence`, `updated_at`, `created_at`) values (25, 1, 1, 2019-04-28 14:24:48, 2019-04-28 14:24:48))
  </code></pre>
  
  <p>according to error, it tries to write data on <code>students</code> table but I want to write them on <code>student_session</code> table!  </p>
  
  <p>what is wrong in my codes?</p>