Under the hood, the withAvg/withCount/withSum and other methods in Eloquent use the 'withAggregate' method. You can use this method to add a subselect based on a relationship
1// Eloquent Model 2class Post extends Model 3{ 4 public function user() 5 { 6 return $this->belongsTo(User::class); 7 } 8} 9 10// Instead of eager loading all users...11$posts = Post::with('user')->get();12 13// You can add a subselect to only retrieve the user's name...14$posts = Post::withAggregate('user', 'name')->get();15 16// This will add a 'user_name' attribute to the Post instance:17$posts->first()->user_name;
Tip given by @pascalbaljet