PHP code example of brainstud / json-api-resource

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/ */

    

brainstud / json-api-resource example snippets


class Resource extends JsonApiResource
{
    protected string $type = 'resources';

    protected function toAttributes(Request $request): array
    {
        return [
            'field' => $this->resource->field,
            'other_field' => $this->resource->other_field,
        ];
    }

    protected function toRelationships(Request $request): array
    {
        return [
            'relation' => ['relationMethod', Relation::class],
        ];
    }

    protected function toLinks(Request $request): array
    {
        return [
            'type_of_link' => ['href' => 'link'],
        ];
    }

    protected function toMeta(Request $request): array
    {
        return [
            'meta' => 'data',
        ];
    }
}

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,
    \Brainstud\JsonApi\Handlers\JsonApiExceptionHandler::class
);

// 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);
    }
}

protected function register(): array
{
    return [
        'id' => $this->resource->identifier,
        'type' => 'object_type',
        'attributes' => [
            'field' => $this->resource->field,
            'other_field' => $this->resource->other_field,
        ],
        'relationships' => [
            'items' => ['items', ItemsResourceCollection::class],
            'item' => ['item', ItemResource::class],
        ],
        'meta' => [
            'some_data' => 'some value',
        ],
        'links' => [
            'some_key' => 'some link',
        ],
    ];
}

protected function addToResponse($request, $response): array
{
    if ($this->requestWantsMeta($request, 'data')
        && ($data = $this->getData())
    ) {
        $response['meta']['data'] = $data;
    }

    return $response;
}