title: Laravel 5 Eloquent: How do I sort db rows and also get rank?
body: <p>I have a user and referral table with a one-to-many relationship.  I'm trying to get the rank of a user based on referral count compared to other users. I only got as far as being able to list the users according to their referral count. </p>
  
  <pre><code>$users = App\User::with('referrals')-&gt;get()-&gt;sortBy(function($user)
  {return $user-&gt;referrals-&gt;count();});
  </code></pre>
  
  <p>But I don't know how to get the rank or sort the rows based on referral count.</p>
  
  <p>this is my referral table :</p>
  
  <pre><code>    Schema::create('referrals',function(Blueprint $table){
          $table-&gt;increments('id');
          $table-&gt;bigInteger('user_id');
          $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users');  
          $table-&gt;bigInteger('referral_id');
          $table-&gt;timestamps();
      });
  </code></pre>
  
  <p>So for example if I have this in my db</p>
  
  <pre><code>user id 1 | 5 referrals
  user id 2 | 10 referrals
  user id 3 | 1 referral
  </code></pre>
  
  <p>I want to be able to get the rank of user id 2, which is 1.</p>