Level 58
To create an API resource for the $courses query, you can follow these steps:
- Create a new resource using the
php artisan make:resourcecommand:
php artisan make:resource CourseResource
- In the
toArraymethod of theCourseResourceclass, you can format the output of the$coursesquery as needed. For example:
public function toArray($request)
{
return [
'title' => $this->title,
'count' => $this->count(),
'items' => $this->map(function ($item) {
return [
'id' => $item->id,
'name' => $item->name,
// add any other fields you need
];
}),
];
}
- In your controller, you can use the
CourseResourceclass to format the output of the$coursesquery:
use App\Http\Resources\CourseResource;
$courses = Content::query()->exposed()->get()->groupBy('title');
return CourseResource::collection($courses);
This will return a JSON response with the formatted output of the $courses query, grouped by title.