title: Get latest message (row) per user in Laravel
body: <p>TL;DR: Need latest message from each sender.</p>
  
  <p>In my Laravel application I have two tables:</p>
  
  <p>Users:</p>
  
  <ul>
  <li>id</li>
  <li>name</li>
  </ul>
  
  <p>Messages:</p>
  
  <ul>
  <li>id</li>
  <li>sender_id</li>
  <li>recipient_id</li>
  <li>body</li>
  <li>created_at</li>
  </ul>
  
  <p>And of course models.</p>
  
  <p>User model:</p>
  
  <pre><code>public function messages() {
      return $this-&gt;hasMany('App\Message', 'recipient_id');
  }
  </code></pre>
  
  <p>Messages model:</p>
  
  <pre><code>public function sender() {
      return $this-&gt;belongsTo('App\User', 'sender_id');
  }
  
  public function recipient() {
      return $this-&gt;belongsTo('App\User', 'recipient_id');
  }
  </code></pre>
  
  <p>When user opens his inbox, he should see list of latest message from any other user.</p>
  
  <p>So if there are messages:</p>
  
  <pre><code>id sender_id recipient_id body created_at
  1, 2,        1,           hi,  2016-06-20 12:00:00
  2, 2,        1,           hi,  2016-06-21 12:00:00
  3, 3,        1,           hi,  2016-06-20 12:00:00
  4, 3,        1,           hi,  2016-06-21 12:00:00
  </code></pre>
  
  <p>Then user with id 1 (recipient_id) should see only messages with id 2 and 4.</p>
  
  <p>This is current solution in Users model:</p>
  
  <pre><code>return Message::whereIn('id', function($query) {
                  $query-&gt;selectRaw('max(`id`)')
                  -&gt;from('messages')
                  -&gt;where('recipient_id', '=', $this-&gt;id)
                  -&gt;groupBy('sender_id');
              })-&gt;select('sender_id', 'body', 'created_at')
              -&gt;orderBy('created_at', 'desc')
              -&gt;get();
  </code></pre>
  
  <p>This is working, but I was wandering if it is possible to achieve this the Laravel way. Probably with eager loading. My Laravel skills just not enough and after several days of trying I don't have a solution.</p>
  
  <p>Thanks.</p>