PHP code example of yzen.dev / laravel-json-api-response

1. Go to this page and download the library: Download yzen.dev/laravel-json-api-response 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/ */

    

yzen.dev / laravel-json-api-response example snippets


use YzendDev\Laravel\JsonApiResponse\Responder\AbstractResponder;

/**
 * @extends AbstractResponder<User>
 */
final class UserResponder extends AbstractResponder
{
    protected function resourceType(): string
    {
        return 'User';
    }

    protected function composeAttributes(mixed $entity): array
    {
        return [
            'name' => $entity->name,
            'isActive' => $entity->is_active,
            'createdAt' => $entity->created_at->toIso8601String(),
        ];
    }
}

$response = (new UserResponder())->compose($user);

[
    'data' => [
        'id' => 10,
        'type' => 'User',
        'attributes' => [
            'name' => 'yzen.dev',
            'isActive' => true,
            'createdAt' => '2026-05-15T12:00:00+00:00',
        ],
    ],
]

use YzendDev\Laravel\JsonApiResponse\Responder\RelationshipDefinition;

protected function relationships(): array
{
    return [
        'countryFrom' => new RelationshipDefinition('country_from_id', CountryResponder::class),
        'cityFrom' => new RelationshipDefinition('city_from_id', CityResponder::class),
    ];
}

$countries = [
    10 => $country,
    11 => $anotherCountry,
];

$responder = (new UserResponder())
    ->withRelationData('countryFrom', $countries);

use YzendDev\Laravel\JsonApiResponse\Responder\ToManyRelationshipDefinition;

protected function relationships(): array
{
    return [
        'pickups' => new ToManyRelationshipDefinition('id', PickupResponder::class),
    ];
}

$pickups = [
    5 => [
        $pickupA,
        $pickupB,
    ],
    6 => [
        $pickupC,
    ],
];

$responder = (new UserResponder())
    ->withRelationData('pickups', $pickups);

$responder = (new UserResponder())
    ->withRelationData('pickups', $pickups)
    ->withNestedRelationData('pickups', 'city', [
        7 => $hamburg,
        8 => $berlin,
    ]);

use YzendDev\Laravel\JsonApiResponse\Responder\IncludeDefinition;

protected function 
}

$responder = (new SomeResponder())->withIncludeData('units', [
    $unitA,
    $unitB,
]);

$payload = (new UserResponder())->composeList($paginator);

[
    'meta' => [
        'totalRecords' => 50,
        'perPage' => 15,
        'currentPage' => 2,
        'lastPage' => 4,
    ],
]

use YzendDev\Laravel\JsonApiResponse\Responder\JsonResponse;

return new JsonResponse($payload);

use YzendDev\Laravel\JsonApiResponse\Responder\JsonResponse;

return new JsonResponse(
    status: JsonResponse::HTTP_OK,
    data: new UserResponder()->compose($request->user()),
);

use YzendDev\Laravel\JsonApiResponse\Responder\ValidationErrorsResponder;

$errors = (new ValidationErrorsResponder())->compose([
    'email' => ['The email field is 

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use YzendDev\Laravel\JsonApiResponse\Responder\JsonResponse;
use YzendDev\Laravel\JsonApiResponse\Responder\Types\AuthenticationJsonApiException;
use YzendDev\Laravel\JsonApiResponse\Responder\Types\AuthorizationJsonApiException;
use YzendDev\Laravel\JsonApiResponse\Responder\Types\ResourceConflictJsonApiException;
use YzendDev\Laravel\JsonApiResponse\Responder\Types\ResourceNotFoundJsonApiException;
use YzendDev\Laravel\JsonApiResponse\Responder\ValidationErrorsResponder;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(fn (AuthenticationException $e) => new AuthenticationJsonApiException());
        $exceptions->render(fn (AuthorizationException $e) => new AuthorizationJsonApiException());
        $exceptions->render(fn (AccessDeniedException $e) => new AuthorizationJsonApiException());

        $exceptions->render(function (ValidationException $e) {
            return new JsonResponse(
                status: JsonResponse::HTTP_UNPROCESSABLE_ENTITY,
                data: [
                    'errors' => (new ValidationErrorsResponder())->compose($e->errors()),
                ],
            );
        });

        $exceptions->render(fn (MethodNotAllowedHttpException $e) => new JsonResponse(status: 405));
        $exceptions->render(fn (ResourceNotFoundException $e) => new ResourceNotFoundJsonApiException($e));
        $exceptions->render(fn (NotFoundHttpException $e) => new ResourceNotFoundJsonApiException($e));
        $exceptions->render(fn (ModelNotFoundException $e) => new ResourceNotFoundJsonApiException($e));
        $exceptions->render(fn (FileNotFoundException $e) => new ResourceNotFoundJsonApiException($e));
        $exceptions->render(fn (ResourceConflictException $e) => new ResourceConflictJsonApiException($e));
    })
    ->create();

if (! $user) {
    throw new ResourceNotFoundException('User was not found.');
}