craigivemy
1 month ago
272
4
Laravel

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

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.

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