1. Go to this page and download the library: Download brainstud/json-api-resource library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
public function show(ShowCourseRequest $request, Course $course)
{
$query = (new CoursesQueryBuilder)->find($course->id);
return new CourseResource([$query, 3]);
}
// app.php
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
// handler.php
public function render($request, Throwable $exception)
{
if ($request->wantsJson()) {
return (new JsonApiExceptionHandler($this->container))->render($request, $exception);
}
return parent::render($request, $exception);
}
// Throw an exception that will be handled by the JsonApiExceptionHandler
throw new UnprocessableEntityHttpException();
// Return a defined error response
return (new UnprocessableEntityError)->response();
// Return a custom error response
return ErrorResponse::make(new DefaultError(
'PROCESSING_ERROR',
'Could not save item',
'An error occurred during saving of the item'
), Response::HTTP_INTERNAL_SERVER_ERROR);
// Course.php
/**
* @property int $id
* @property string $title
* @property string $description
* @property Carbon $created_at
* @property Collection $enrollments
*/
class Course extends Model
{
protected $fillable = [
'title',
'description',
];
public function enrollments(): HasMany
{
return $this->hasMany(Enrollment::class);
}
}
// CourseResource.php
/**
* @property Course $resource
*/
class CourseResource extends JsonApiResource
{
protected string $type = 'courses';
protected function toAttributes(Request $request): array
{
return [
'title' => $this->resource->title,
'description' => $this->resource->description,
'created_at' => $this->resource->created_at->format('c'),
];
}
protected function toRelationships(Request $request): array
{
return [
'enrollments' => ['enrollments', EnrollmentResourceCollection::class],
];
}
protected function toLinks(Request $request): array
{
return [
'view' => ['href' => $this->resource->getShowUrl()],
];
}
protected function toMeta(Request $request): array
{
return [
'enrollments' => $this->resource->enrollments->count(),
];
}
}
// CoursesController.php
class CoursesController
{
public function index(IndexCoursesRequest $request)
{
$query = (new CoursesQueryBuilder)->jsonPaginate();
return new CourseResourceCollection($query);
}
public function show(ShowCourseRequest $request, Course $course)
{
$query = (new CoursesQueryBuilder)->find($course->id);
return new CourseResource($query);
}
}