Anatomy of a resource
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.
| Hook | Renders | Default |
|---|---|---|
toType() | type | #[JsonApiType], otherwise the class name through type.naming |
toIdentifier() | id, as a string | toId() when not null, otherwise the model key |
toAttributes() | attributes | The model's attributesToArray(), without its key, id, type and the foreign keys of the declared relationships |
toRelationships() | relationships | none |
toLinks() | links of the resource object | none, or those of #[JsonApiRoutes] |
toResourceMeta() | meta of the resource object | none |
toDocumentMeta() | top-level meta, from the primary resources only | none |
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:
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.idandtypeare 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.naming | Type |
|---|---|
kebab-singular (default) | blog-post |
kebab-plural | blog-posts |
snake-plural | blog_posts |
a class implementing Ark4ne\JsonApi\Configuration\TypeNaming | its 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 theBelongsTorelations; - the relationships from the public methods typed with a relation (
'user' => $this->one()); aMorphTois left as a comment, to complete with its resources.
php artisan vendor:publish --tag=jsonapi-stubs publishes the stub to customise it.