0

之前我在 Laravel 中使用了纯 graphQL,我没有遇到任何问题,因为整个验证可以在 ../GraphQL/mutations/ 中的文件中完成。然而,我现在已经开始使用灯塔,而且很多事情都做了不同的处理。例如,我有这个突变:

type Mutation {
  createUser(
    name: String @rules(apply: ["required", "min:2"])
    age: Int!
  ): User @create
}

如何在此处添加自己的验证?例如,我希望用户的年龄至少比当年早 10 年。

4

1 回答 1

0

Following the lighthouse validation in docs you first you add @validator to the schema.

type Mutation {
  createUser(
    name: String
    age: Int!
  ): User @create @validator
}

Then you create that validator with php artisan lighthouse:validator CreateUserValidator. On the file, you do the before laravel validation rule.

<?php

namespace App\GraphQL\Validators;

use Nuwave\Lighthouse\Validation\Validator;

class CreateUserValidator extends Validator
{
    /**
     * Return the validation rules.
     *
     * @return array<string, array<mixed>>
     */
    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'min:2'
            ],
            'age' => [
                'required',
                'date',
                'before:-10 years'
            ],
        ];
    }
}
于 2021-06-13T22:48:09.213 回答