title: Eager loading with many to many relationship in laravel 4
body: <p>I'm trying to set up at messaging system in laravel 4. I have two classes Conversation and User with a many to many relationship between them. I'm outputting a list of a logged in user's conversations and the users in the conversations:</p>
  
  <pre><code>@foreach(User::find(Auth::user()-&gt;id)-&gt;conversations as $conversation) 
  
      {{ $conversation-&gt;id }}
  
      @foreach($conversation-&gt;users as $user) 
          {{ $user-&gt;name }}
      @endforeach   
  
      &lt;br&gt;&lt;br&gt;
  
  @endforeach
  </code></pre>
  
  <p>This is working and outputs the conversation id followed by the name of the users participating in that conversation. My problem is that this way a lot of queries are run and I can't figure out how to use eager loading and still be able to select only the logged in users conversations. Any help would be much appreciated!  </p>
  
  <p>Edit:</p>
  
  <p>With the following code I get the right output, but still queries the database a lot:</p>
  
  <pre><code>&lt;?php $user = User::with('conversations')-&gt;find(Auth::user()-&gt;id); ?&gt;
  
  {{ $user-&gt;username }}'s conversations&lt;br&gt;&lt;br&gt;
  @foreach($user-&gt;conversations as $conversation) 
      {{ $conversation-&gt;id }} 
      @foreach($conversation-&gt;users as $user) 
          {{ $user-&gt;name }}
      @endforeach
      &lt;br&gt;
  @endforeach
  </code></pre>
  
  <p>I would really like to be able to eager load this part @foreach($conversation->users as $user). It outputs:</p>
  
  <p>user_1's conversations</p>
  
  <p>1 user_1 user_2 </p>
  
  <p>5 user_1 user_3</p>