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
// Eloquent Model
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Avoid eager-loading every user when only a name is needed.
$posts = Post::with('user')->get();
// Select only the related user name with a subquery.
$posts = Post::withAggregate('user', 'name')->get();
// This adds a user_name attribute to each Post model:
$posts->first()->user_name;