1 month ago

API Resource: Using count() with whenLoaded()

Posted 1 month ago by craigivemy

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')


$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);

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.

Please sign in or create an account to participate in this conversation.