Laravel sorting 1st level collection by 2nd level value
<p>I have users with (or without) posts and I want the order of users to be dictated by the last post (showing the users who have never posted, then posted the longest ago first).</p>

<p>User A has posted yesterday<br />
User B posted a week ago.<br />
User C has never posted.</p>

<p>The order of users should be C,B,A.</p>

<p>The following code is how far I've come, but I can't seem to get it right. The order of users is not as I would expect it to be. Any thoughts?</p>

<p><strong>UPDATE:</strong><br />
After removing the limit() on eager-load, The result of sorting is:
C,A,B, instead of C,B,A.</p>

<pre><code>$users = User::with('roles', 'flags')-&gt;whereHas('subscription', function($x) use($category_id) {
    $x-&gt;where('subscription.category_id', '=', $category_id);
})-&gt;get()-&gt;load([
    'posts' =&gt; function($y) {
        return $y-&gt;orderBy('created_at', 'ASC');
    }
]);

$users = $users-&gt;sortBy(function($user) {
    if(count($user-&gt;posts) == 0) {
        return 0;
    }

    return strtotime($user-&gt;posts[0]-&gt;created_at);
});

return $users;
</code></pre>