Example 13-24. Conditionally loading API relationship
<?phpnamespaceApp\Http\Resources;useIlluminate\Http\Resources\Json\ResourceCollection;classDogCollectionextendsResourceCollection{/** * Transform the resource collection into an array. * * @param\Illuminate\Http\Request $request * @returnarray */publicfunctiontoArray($request) {return ['name'=>$this->name,'breed'=>$this->breed,// Only load this relationship if it's been eager-loaded'bones'=>BoneResource::collection($this->whenLoaded('bones')),// Or only load this relationship if the URL asks for it'bones'=>$this->when( $request->get('include')=='bones',BoneResource::collection($this->bones)), ]; }}