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