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

vincent15000's avatar

SortBy on a collection resource ?

Hello,

I discover the resources and collections for the API. And I need to sort the result by a specific column.

Here is my code.

class TeachingUnitResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'hours_number' => $this->hours_number,
            'comments' => $this->comments,
            'subjects' => TeachingUnitSubjectResource::collection($this->teachingUnitSubjects->sortBy('name'))
        ];
    }
}

The problem is that teaching_unit_subject is a pivot table and name is not in the pivot table (it is in the subjects table).

How is it possible to sort by name without having to write a specific query ?

Thanks a lot ;).

V

0 likes
10 replies
anilkumarthakur60's avatar
Level 6
$collection_list->sortBy('column_name') ->get() // asc order
$collection_list->sortByDesc('column_name')->get() //desc order

1 like
vincent15000's avatar

Hello thanks that's ok for me, but the column is not in the pivot table, then it doesn't work ;).

vincent15000's avatar

Hello @silencebringer the relationship between teaching units and subjects is many-to-many and the pivot table is teaching_unit_subjects.

SilenceBringer's avatar

@vincent15000 this way when you call subjects relation on TechingUnit model you should have subjects collection and be able to sort it by name. what's the problem?

1 like
ademtepe's avatar

I solved my problem like this:

$activityResourceCollection = ActivityResource::collection($activities);
$activities = $activityResourceCollection->toArray($request);
$activities = collect($activities)->sortBy('distanceInMeters');

distanceInMeters is calculated and added in the resource.

1 like

Please or to participate in this conversation.