Skip to content

JSON:API resources ​

Laravel 12 and 13 ship Illuminate\Http\Resources\JsonApi\JsonApiResource. The package works with it and adds one fix for narrowed selects.

Strict models and sparse fieldsets ​

Laravel's JsonApiResource reads every attribute it lists before it applies fields[<type>]. With Model::preventAccessingMissingAttributes() (or Model::shouldBeStrict()), a model loaded with a narrowed SELECT then throws MissingAttributeException.

Extend MyProgs\QueryBuilder\Resources\JsonApiResource instead, or use its MyProgs\QueryBuilder\Resources\LazyAttributes trait in your own base resource: an attribute listed by name is then read only when the response keeps it.

php
use MyProgs\QueryBuilder\Resources\JsonApiResource;

class ArticleResource extends JsonApiResource
{
    public $attributes = ['title', 'body', 'views'];

    public $relationships = ['author', 'comments'];
}

Matching types ​

The resource narrows its attributes by fields[<type>] with the type it derives from its class name, while the query narrows the SELECT by the keys of the definition. Keep them the same: give the definition the type() of the resource, and describe an included relation by a definition of that type (Relationship::to('author', UserQuery::class)), so the fields[users] a JSON:API client sends reaches it.