title: Laravel eloquent sort query
body: <p>I'm trying to <strong>sort</strong> the users from my users table <strong>by</strong> the combined value of their distance in the activities table. The following code returns something like this.</p>
  
  <p><a href="https://i.stack.imgur.com/eoM2i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eoM2i.png" alt=""></a></p>
  
  <p>I'm trying to figure out <strong>how to sort</strong> this data by the sum_distance value.
  Also I can't seem to figure out <strong>how to display</strong> just the sum_distance data as $item->sum_distance doesn't return anything. (because it's nested inside somewhere I guess)</p>
  
  <p>User model</p>
  
  <pre><code>protected $fillable = ['strava_id', 'first_name', 'last_name', 'sex', 'avatar', 'email', 'token'];
  
  public function sumDistance()
  {
      return $this-&gt;hasMany('App\Activity')
          -&gt;selectRaw('user_id, sum(distance) as sum_distance')
          -&gt;groupBy('user_id')
          -&gt;orderBy('sum_distance', 'desc');
  }
  </code></pre>
  
  <p>Activity model</p>
  
  <pre><code>protected $fillable = ['activityId', 'user_id', 'name', 'distance', 'moving_time', 'start_date'];
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>public function index(Strava $strava)
  {
  
      $list = User::with('sumDistance')-&gt;get();
  
      return view('leaderboard', compact('list'));
  
  }
  </code></pre>
  
  <p>View</p>
  
  <pre><code>&lt;ul&gt;
      @foreach($list as $item)
          &lt;li&gt;{{ $item }}&lt;/li&gt;&lt;br&gt;
      @endforeach
  &lt;/ul&gt;
  </code></pre>