title: Laravel order data by relation property
body: <p>I have two related models 'Yards' &amp; 'Inspections'. A yard can have multiple inspections.</p>
  
  <p>I want to be able to order the Yard list based on the inspection property 'reinspect_at'. I have a Model method that returns the Latest Inspection for the yard based on the inspection date.</p>
  
  <p>I have tried the following:</p>
  
  <pre><code>$yards = Yard::orderBy('quarantined', 'DESC')
          -&gt;with(['latestInspection' =&gt; function($query){
              $query-&gt;orderBy('reinspect_at', 'asc');
          }])
          -&gt;get();
  </code></pre>
  
  <p>But this doesn't order the yard based on the reinspect_at date, it is only ordering the latest inspection for each yard.</p>
  
  <p>I want to be able to always return the latest inspection for the yard, but need to be able to reorder the yard list based on the reinspect_at date for the latest inspection for each yard. Cheers</p>
  
  <p>Screenshot of yard list display below. As you can see the Inspection due date is how I want to be able to order the result.</p>
  
  <p><a href="https://i.stack.imgur.com/3OQwE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3OQwE.png" alt="enter image description here"></a></p>
  
  <p>** Update **
  Looks like what I want is possible in the frontend template using:</p>
  
  <pre><code>@foreach( $yards-&gt;sortBy('latestInspection.reinspect_at') as $yard )
  </code></pre>
  
  <p>It would be preferable to do be able to do this from the controller though, so I can have other options for ordering by.</p>