Resources

Collections & pagination

Collections of resources, their document meta, and Laravel's paginators.

UserResource::collection($models) returns a JsonApiCollection, used like Laravel's resource collections:

return UserResource::collection(User::all());

A collection of your own

app/Http/Resources/UserCollection.php
use Ark4ne\JsonApi\Resources\JsonApiCollection;

final class UserCollection extends JsonApiCollection
{
    public $collects = UserResource::class;

    protected function toDocumentMeta(Request $request): ?iterable
    {
        return ['total' => fn() => $this->collection->count()];
    }
}

Its toDocumentMeta() wins over those of its resources.

Pagination

A paginated collection keeps the output of Laravel's paginators (paginate(), simplePaginate(), cursorPaginate()):

return UserResource::collection(User::query()->paginate()); // ?page=2
  • The links named by the specification: first, last, prev, next. A link a paginator cannot give is null: last for simplePaginate(), first and last for cursorPaginate(), prev and next at the ends.
  • The meta of Laravel's paginator.

The specification fixes no format for page, sort and filter: handle them as in any Laravel API. It requires a 400 Bad Request for an unsupported sort.