A collection of tools for working with JSON:API data. This package is an extension of focus/data.
The best way to install and use this package is with composer:
composer require focus/json-api
This package provides some structure to reading JSON:API formatted data. Both resource and resource collections are supported.
The typical entry point will be DocumentData
:
use Focus\JsonApi\DocumentData;
$data = DocumentData::fromRequest($request);
Note: Like JsonData
, this package supports reading JSON from
strings and PSR-7 request and response objects.
Once the document is created, the primary data can be accessed as a resource:
$book = $data->resource();
var_dump($book->attribute(path: 'title'));
var_dump($book->attribute(path: 'subtitle'));
var_dump($book->relation(name: 'author'));
Or a collection of resources:
$books = $data->collection();
var_dump($books->ids());
Or the included resources:
$publishers = $data->included(type: 'publisher');
var_dump($publishers->ids());
The Identifier
object extends Data
and adds helper methods to read
the type and identifier value:
$id = $data->id();
$type = $data->type();
The Resource
object extends from Identifier
and adds helper methods to read
attributes and relationships:
$id = $data->id();
$topics = $data->attribute(path: 'topics');
$author = $data->relation(name: 'author');
$publishers = $data->relations(name: 'publishers');
- The value of
relation()
is an identifier of a to-one relationship. When the relationship is undefined,null
will be returned. When the relationship is defined asnull
, a blankIdentifier
will be returned. - The value of
relations()
is an identifier collection of a to-many relationship. When the relationship is undefined,null
will be returned. When the relationship is defined asnull
, an emptyIdentifierCollection
will be returned.
The return values of relation()
and relations()
are structured this way to allow
determining when a relationship is not present (undefined) versus being unset (null).
The IdentifierCollection
object represents a collection of Identifier
objects
and adds helper methods to read the identifier values:
var_dump($publishers->ids());
The collection can also be iterated:
foreach ($publishers as $publisher) {
var_dump($publisher->id());
var_dump($publisher->type());
}
The ResourceCollection
object represents a collection of Resource
objects
and adds helper methods to read the identifier values:
var_dump($publishers->ids());
The collection can also be iterated:
foreach ($publishers as $publisher) {
var_dump($publisher->id());
var_dump($publisher->attribute(path: 'name'));
}