0

Earlier I used pure graphQL for Laravel and I didn't have a problem with it, because the whole validation could be done in files in ../GraphQL/mutations/. However, I have now started using the lighthouse and many things are done differently. For example, I have this mutation:

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

How can I add my own validation here? For example, I would like the user's age to be at least 10 years back from the current year.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

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'
            ],
        ];
    }
}
francisco
  • 1,387
  • 2
  • 12
  • 23