However, I would like to apply a sort order to the returned relationship.
In the example below, if I used the sortBy method, it works if I include the relationship. But if I ever call the resource without loading the images relationship, I get an error that says "Call to undefined method Illuminate\Http\Resources\MissingValue::sortBy()",
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'images' => ImageResource::collection($this->whenLoaded('images')->sortBy('sort_order')),
];
}
Would really appreciate any help on how to solve this.