Requests

Write requests

Validate the resource object of a POST or PATCH body and read it in the controller.

A write request validates its body with ordinary rules, keyed by the path of each member. $request->jsonApi() then reads the resource object from the validated data.

app/Http/Requests/PostStoreRequest.php
final class PostStoreRequest extends JsonApiFormRequest
{
    protected string $resource = PostResource::class;

    public function rules(): array
    {
        return [
            'data.type' => ['required', 'in:post'],
            'data.attributes.title' => ['required', 'string'],
            'data.relationships.user.data.id' => [
                'required',
                'exists:users,id',
            ],
            'data.relationships.tags.data' => ['sometimes', 'array'],
            'data.relationships.tags.data.*.id' => [
                'required',
                'exists:tags,id',
            ],
        ];
    }
}
app/Http/Controllers/PostController.php
public function store(PostStoreRequest $request): PostResource
{
    $document = $request->jsonApi();

    $document->type();                  // 'post'
    $document->id();                    // null: no client-generated id
    $document->attributes();            // ['title' => '…']
    $document->attribute('title');      // '…'
    $document->relationship('user');    // ['id' => 1]: the linkage, as sent
    $document->ids('user');             // ['1']: the ids, as strings
    // false when not sent, true for 'data' => [] (every tag detached)
    $document->hasRelationship('tags');
    $document->ids('tags');             // []

    // …
}
  • A member without rule is missing from jsonApi().
  • To read a relationship that is cleared ("data": null, or [] for a to-many), give its linkage a rule of its own (data.relationships.tags.data): the rules of its identifiers alone leave it out of the validated data.
  • Validation errors are keyed by the path of the member, and rendered with a source.pointer (/data/attributes/title).

ResourceDocument also offers hasAttribute(), relationships() and meta().

Bodies that change across revisions

When the body a client sends depends on its revision, declare it in body() instead of rules(): see Write requests across revisions.