Resources

Anatomy of a resource

The hooks of a resource, and why they describe values instead of computing them.

A resource extends Ark4ne\JsonApi\Resources\JsonApiResource. It is still a Laravel JsonResource: return it from a controller, call make() or collection() as usual.

The hooks

Every hook is optional.

HookRendersDefault
toType()type#[JsonApiType], otherwise the class name through type.naming
toIdentifier()id, as a stringtoId() when not null, otherwise the model key
toAttributes()attributesThe model's attributesToArray(), without its key, id, type and the foreign keys of the declared relationships
toRelationships()relationshipsnone
toLinks()links of the resource objectnone, or those of #[JsonApiRoutes]
toResourceMeta()meta of the resource objectnone
toDocumentMeta()top-level meta, from the primary resources onlynone
app/Http/Resources/UserResource.php
use Ark4ne\JsonApi\Resources\JsonApiResource;
use Illuminate\Http\Request;

/**
 * @extends JsonApiResource<User>
 */
final class UserResource extends JsonApiResource
{
    public function toAttributes(Request $request): iterable
    {
        return [
            'name' => $this->string(),
            'email' => $this->string(),
        ];
    }

    protected function toResourceMeta(Request $request): ?iterable
    {
        return [
            'created_at' => $this->datetime(),
            'updated_at' => $this->datetime(),
        ];
    }

    protected function toRelationships(Request $request): iterable
    {
        return [
            'posts' => $this->many(PostResource::class),
            'comments' => $this->many(CommentResource::class)->whenLoaded(),
        ];
    }
}

Describe, do not compute

toAttributes(), toRelationships(), toResourceMeta() and toDocumentMeta() run once per response, on a template whose $this->resource is set to each model before its values are read. So every member is declared, under its name:

  • a descriptor: $this->string(), $this->one(UserResource::class)…, typed and read only when the member is requested;
  • or a closure: a value of any type, computed for each resource.
return [
    // read from `name`
    'name' => $this->string(),
    // read from another key
    'mail' => $this->string('email'),
    // any value, per resource
    'hash' => fn() => base64_encode($this->resource->email),
    // refused: the same for every resource
    'name' => $this->resource->name,
];

A plain value, a member without name, and Laravel's $this->when() / $this->mergeWhen() are refused with a DefinitionException.

The definition

The package reads what a resource declares (type, attributes, relationships, eager-loads) once per class, without a model: it runs the hooks on a probe standing for the model, with an empty request. This definition validates include and fields, plans the eager-loads, and is returned by UserResource::definition(). Hence:

No if on the request or the model in a hook. The definition sees an empty request: a member added under an if is missing from it, so fields and include cannot name it. Write conditions with ->when(), ->unless() or $this->applyWhen(), see Conditions.
  • id and type are reserved: never declare them as attributes.
  • Descriptors are immutable: every modifier returns a copy, so chain them or keep the returned value.
  • toArray() is the resource object alone: included, document meta and pagination exist only in the response.

php artisan jsonapi:check reports what breaks these rules, and php artisan jsonapi:cache (run by optimize) compiles every definition for production.

Type and identifier

protected function toType(Request $request): string
{
    return 'user';
}

Without toType(), the type is that of the #[JsonApiType] attribute:

use Ark4ne\JsonApi\Resources\Attributes\JsonApiType;

#[JsonApiType('posts')]
final class PostResource extends JsonApiResource {}

Otherwise it follows type.naming, from the class name without its Resource suffix (BlogPostResource):

type.namingType
kebab-singular (default)blog-post
kebab-pluralblog-posts
snake-pluralblog_posts
a class implementing Ark4ne\JsonApi\Configuration\TypeNamingits own

The identifier is toId() when it gives one (the hook of Laravel's native resources, null by default), otherwise the model key. Override toIdentifier() for anything else; it is always rendered as a string.

Generating a resource

php artisan make:jsonapi-resource PostResource writes app/Http/Resources/PostResource.php from the model (--model=Post, otherwise App\Models\Post by convention; --force overwrites):

  • the attributes from the casts ('datetime:Y-m-d H:i' gives $this->datetime()->format('Y-m-d H:i'), 'decimal:2' gives $this->decimal()->scale(2), an enum gives $this->enum()), then the fillable attributes without cast ($this->mixed()) and the timestamps; never the key, id, type, the hidden attributes nor the foreign keys of the BelongsTo relations;
  • the relationships from the public methods typed with a relation ('user' => $this->one()); a MorphTo is left as a comment, to complete with its resources.

php artisan vendor:publish --tag=jsonapi-stubs publishes the stub to customise it.