Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

242Studios's avatar

Sorting Conditional API Resource Relationships

Hi,

I'm using API Resources and conditional relationships as shown in the docs: https://laravel.com/docs/5.7/eloquent-resources#conditional-relationships

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.

-=Chris

0 likes
1 reply
shez1983's avatar

you can sort by in the actual relationship which i assume is defined in this models relationship() function so something like

return $this->hasMany('')->orderBy(sort col);

what is sortBy() your func or laravels? if laravels it should be OrderBy or latest()/oldest()

Please or to participate in this conversation.