title: Pagination with many to many relationship in laravel
body: <p>I'm trying to set up Email system in laravel 4.2. I have two model Email and User with a many to many relationship between them. So far so good but now I just stuck with a problem while paginating send emails. I've been trying for 2 days but didn't accomplish the task yet.</p>
  
  <pre><code>    //User.php    Model
      public function emails()
      {   
          return $this-&gt;belongsToMany('Email', 'users_email', 'reciever_uid','email_id')-&gt;
           withPivot('sender_UID');
      }
  
      //Email.php  Model
      public function users()
      {   
          return $this-&gt;belongsToMany('User', 'users_email', 'email_id','reciever_id');
      }
  </code></pre>
  
  <p>I've tried to fetch the users_email pivot table data to get all the email ids of the current
  authenticated user QueryBuilder.        </p>
  
  <pre><code>    $user=Auth::Id();
      $user_data=DB::table('users_email')-&gt;
      join('users','users_email.reciever_uid','=','users.Id')-&gt;
      where('users_email.sender_uid','=',$user-&gt;Id)-&gt;orderby   
      ('users_email.email_id','desc')-&gt;get();
  
      foreach ($user_data as $data) {
      $id[]=$data-&gt;email_id;
     }
  </code></pre>
  
  <p>Now I have $id array and I want to fetch all the emails along with the f_name and l_name of the receiver to be displayed.
  So far I've tried eager loading with some basic knowledge but couldn't get the
  expected result. I've tried something this to paginate all the emails within
  $id but getTotal returns only 2 even though the picture shown below specifies that the email with id=78 had sent 8 n more so I want to paginate via emails.
  E.x prepage only 10 emails.</p>
  
  <pre><code>    $pagination=User::with(array('emails'=&gt;function($query) use ($id){
          $query-&gt;WhereIn('users_email.email_id',$id);
      }))-&gt;paginate(10);
  </code></pre>
  
  <p>Any help would highly be appreciated.</p>
  
  <p>Thank you</p>
  
  <p>Pivot Table users_email </p>
  
  <p><img src="https://i.stack.imgur.com/zPyav.png" alt="enter image description here"></p>