$collection_list->sortBy('column_name') ->get() // asc order
$collection_list->sortByDesc('column_name')->get() //desc order
Jun 6, 2021
10
Level 63
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
Level 6
1 like
Please or to participate in this conversation.