sahar_mkr's avatar

api resource

Hi everyone, I have this query, how can I write a resource to show the output?

$courses = Content::query()->exposed()->get()->groupBy('title');
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To create an API resource for the $courses query, you can follow these steps:

  1. Create a new resource using the php artisan make:resource command:
php artisan make:resource CourseResource
  1. In the toArray method of the CourseResource class, you can format the output of the $courses query 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
            ];
        }),
    ];
}
  1. In your controller, you can use the CourseResource class to format the output of the $courses query:
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.

Please or to participate in this conversation.