Level 63
To do that, I create an API collection and an API resource and I return the collection.
Here is an example.
Course resource
public function toArray($request)
{
return [
'id' => $this->id,
'unit_name' => $this->topic->unit->name,
'topic_name' => $this->topic->name,
'topic_background_color' => $this->topic->background_color,
'topic_text_color' => $this->topic->text_color,
'date_fr' => $this->date_fr,
'time_range_fr' => $this->time_range_fr,
'hours_number' => $this->hours_number,
'room_name' => $this->room->name ?? null,
'can_update' => auth()->user()->can('update', $this->resource),
'can_delete' => auth()->user()->can('delete', $this->resource),
];
}
Course collection
public function toArray($request)
{
return parent::toArray($request);
}
public function with($request)
{
return [
'meta' => [
'can_create' => auth()->user()->can('create', Course::class),
],
];
}
Controller
return new CourseCollection(Course::
with('topic.unit', 'room')
->where('training_id', $training->id)
->when($topicIds, function ($query) use ($topicIds) {
$query->whereIn('topic_id', $topicIds);
})
->orderByDesc('datetime')
->paginate(10);
Then in the returned collection you will have all pagination datas you need to handle this in the frontend.