title: Laravel getting latest field in Join table with Eager loading
body: <p>Laravel version:7.0</p>
  <p>I am going to get list from <code>Guest</code> model.</p>
  <pre><code>guests table: id, name, status, created_at, updated_at
  
  $guests = Guest::orderby(&quot;status&quot;)-&gt;get();
  </code></pre>
  <p>Here is <code>messages</code> table.</p>
  <pre><code>$messages table: id, message, from_id, from_type, to_id, to_type
  </code></pre>
  <p><code>from_type</code>, <code>to_type</code> can be either guest or user.</p>
  <p>If I get latest message with lazy loading, I can get as following.</p>
  <pre><code>  foreach($guests as $guest)
    {
      $lastMessage = Message::where(function($query) use($guest){
                        $query-&gt;where(&quot;from_id&quot;, $guest-&gt;id);
                        $query-&gt;where(&quot;from_type&quot;, &quot;guest&quot;);
                    })
                    -&gt;orWhere(function($query) use($guest){
                         $query-&gt;where(&quot;to_id&quot;, $guest-&gt;id);
                         $query-&gt;where(&quot;to_type&quot;, &quot;guest&quot;);
                    })-&gt;latest()-&gt;first();
    }
  </code></pre>
  <p>However, I know this is crazy. How can I get this with Eager loading?</p>
  <p>Can anyone please give me some instruction?</p>