I would look at using the withCount method. It's a trivial db query to get the count this way.
https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to avoid loading a relationship unless it has been eager loaded in my controller. However, I also need the count of that relationship if it has been loaded. The code below works unless I don't eager load, in which case it throws a "call to undefined method missingValue::count error.
API Resource
'playedUpCount'=> $this->whenLoaded('playedUps')->count(),
'playedUps'=> $this->whenLoaded('playedUps')
Controller
$teams = Team::whereIn('id', $teamsInSeasonQuery)
->with(['players' => function($query) use($seasonId) {
$query->withTrashed()->where('season_id', $seasonId);
$query->with(['playedUps' => function($query) use($seasonId) {
$query->where('season_id', $seasonId);
}]);
}])
->get();
I will be using the API resource from other methods in the controller where I do not want to be loading the relationship, yet as I say, when I do this it throws the undefined method error.
Give this a go
'playedUpCount'=> $this->whenLoaded('playedUps', function() {
return $this->playedUps->count()
}),
Please or to participate in this conversation.