withAggregate method

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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord