Requests

Validating requests

Validate include and fields against the definitions of your resources.

JsonApiFormRequest

app/Http/Requests/UserFetchRequest.php
use Ark4ne\JsonApi\Http\JsonApiFormRequest;

final class UserFetchRequest extends JsonApiFormRequest
{
    protected string $resource = UserResource::class;
}

include must match the relationships of UserResource and of the resources it relates to, fields their attributes and relationships. Both may be empty (?include=). An invalid value answers 422, with an error whose source.parameter names it.

Your rules() are added to them. A rule keyed include or fields replaces the preset one (it stays nullable); a nested key (fields.*) is added to it:

use Ark4ne\JsonApi\Http\JsonApiFormRequest;
use Ark4ne\JsonApi\Http\Rules\Includes;

final class PostStoreRequest extends JsonApiFormRequest
{
    protected string $resource = PostResource::class;

    public function rules(): array
    {
        return [
            'data.attributes.title' => ['required', 'string'],
            'include' => [new Includes(PostResource::class, maxDepth: 2)],
        ];
    }
}

The body of a write request is covered in Write requests.

The rules in any form request

use Ark4ne\JsonApi\Http\Rules\Fields;
use Ark4ne\JsonApi\Http\Rules\Includes;
use Illuminate\Foundation\Http\FormRequest;

final class UserFetchRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'include' => ['nullable', new Includes(UserResource::class)],
            'fields' => ['nullable', new Fields(UserResource::class)],
        ];
    }
}
  • Includes validates the paths against the relationships, up to include.max-depth or its maxDepth: argument.
  • Fields validates the fieldsets against the attributes and relationships of the types reachable from the resource.

Both take the revision to validate at (revision: ApiRevision::current()); without it, they validate at the head, whatever the revision of the request. A JsonApiFormRequest uses the revision of the request by itself.

Messages

The messages are translations of the package. Publish them to edit or translate them:

Terminal
php artisan vendor:publish --tag=jsonapi-lang   # lang/vendor/jsonapi/en/validation.php
KeyDefault
jsonapi::validation.fields.invalidThe selected is invalid.
jsonapi::validation.fields.invalid_fields":resource" doesn't have fields ":fields".
jsonapi::validation.fields.invalid_resource":resource" doesn't exist.
jsonapi::validation.includes.invalidThe selected is invalid.
jsonapi::validation.includes.invalid_includes":include" doesn't have relationship ":relation".
jsonapi::validation.includes.invalid_depth":include" is deeper than the maximum include depth of .
jsonapi::validation.linkage.missingThe field must be present, it may be null.