Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Graphql Mutation Validator Bundle Laravel Package

assoconnect/graphql-mutation-validator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add the package via Composer:

    composer require assoconnect/graphql-mutation-validator-bundle
    

    Register the bundle in config/bundles.php (if using Symfony) or ensure it’s auto-discovered in Laravel.

  2. Extend the Base Validator Create a custom validator class extending GraphQLMutationValidator:

    use Assoconnect\GraphQLMutationValidatorBundle\Validator\GraphQLMutationValidator;
    
    class UserCreateValidator extends GraphQLMutationValidator
    {
        protected function getRules(): array
        {
            return [
                'name' => 'required|string|max:255',
                'email' => 'required|email|unique:users',
                'password' => 'required|string|min:8',
            ];
        }
    }
    
  3. Bind the Validator to a Mutation In your GraphQL schema resolver, inject the validator:

    use Assoconnect\GraphQLMutationValidatorBundle\Validator\GraphQLMutationValidatorInterface;
    
    class UserCreateResolver
    {
        public function __construct(
            private GraphQLMutationValidatorInterface $validator
        ) {}
    
        public function resolve($root, array $args)
        {
            $validator = new UserCreateValidator();
            $errors = $validator->validate($args['input']);
    
            if ($errors) {
                throw new ValidationException($errors);
            }
    
            // Proceed with mutation logic
        }
    }
    
  4. First Use Case: Form Validation Use this for validating GraphQL mutations like createUser, updateProfile, etc. The validator handles:

    • Field-level rules (e.g., required, email).
    • Custom error messages.
    • Integration with Laravel’s validation pipeline (if using laravel-bundle).

Implementation Patterns

Workflow: Validation in Mutations

  1. Define Rules Override getRules() in your custom validator to specify rules per field:

    protected function getRules(): array
    {
        return [
            'username' => 'required|unique:users|alpha_dash',
            'age' => 'nullable|integer|min:18',
        ];
    }
    
  2. Custom Error Messages Override getMessages() for localized or custom feedback:

    protected function getMessages(): array
    {
        return [
            'username.required' => 'A username is required.',
            'age.min' => 'You must be at least 18 years old.',
        ];
    }
    
  3. Dynamic Rules Use closures for dynamic validation (e.g., conditional rules):

    protected function getRules(): array
    {
        return [
            'password' => function ($attribute, $value, $fail) {
                if (strlen($value) < 8) {
                    $fail('Password must be at least 8 characters.');
                }
            },
        ];
    }
    
  4. Integration with Laravel If using the laravel-bundle, leverage Laravel’s validation helpers:

    use Illuminate\Support\Facades\Validator;
    
    protected function getRules(): array
    {
        return [
            'email' => ['required', 'email', Rule::unique('users')->ignore($this->userId)],
        ];
    }
    
  5. Reusable Validators Create base validators for shared logic (e.g., BaseUserValidator) and extend them:

    class AdminUserValidator extends BaseUserValidator
    {
        protected function getRules(): array
        {
            return array_merge(parent::getRules(), [
                'role' => 'required|in:admin,superadmin',
            ]);
        }
    }
    

Integration Tips

  • GraphQL Schema Alignment Ensure your validator fields match the GraphQL input type:

    input UserInput {
        name: String!
        email: String!
    }
    
    // Validator rules must include 'name' and 'email'.
    
  • Error Handling Catch ValidationException in your resolver and return GraphQL errors:

    try {
        $this->validator->validate($input);
    } catch (ValidationException $e) {
        return new ErrorResult($e->errors());
    }
    
  • Testing Mock validators in tests:

    $validator = $this->createMock(GraphQLMutationValidatorInterface::class);
    $validator->method('validate')->willReturn([]);
    
    $resolver = new UserCreateResolver($validator);
    

Gotchas and Tips

Pitfalls

  1. Field Mismatch

    • Issue: Validator rules don’t match GraphQL input fields.
    • Fix: Double-check getRules() keys against your GraphQL schema.
  2. Overriding Parent Rules

    • Issue: Extending a validator but forgetting to array_merge parent rules.
    • Fix: Use array_merge(parent::getRules(), [...]) to preserve base rules.
  3. Performance with Complex Rules

    • Issue: Heavy rules (e.g., unique checks) in high-traffic mutations.
    • Fix: Cache validator instances or use Rule::first() for partial checks.
  4. Laravel-Specific Quirks

    • Issue: Using Laravel rules without the laravel-bundle.
    • Fix: Manually implement Laravel’s Rule objects or switch to the bundle.

Debugging

  • Enable Debug Mode Set debug: true in the bundle config to log validation errors:

    # config/packages/assoconnect_graphql_mutation_validator.yaml
    debug: true
    
  • Inspect Raw Errors Dump $validator->validate($data) output to debug rule failures:

    $errors = $validator->validate($input);
    dd($errors); // Array of error messages
    

Extension Points

  1. Custom Validation Logic Override validate() to add pre/post-validation logic:

    public function validate(array $data): array
    {
        $this->preValidate($data);
        $errors = parent::validate($data);
        $this->postValidate($data, $errors);
        return $errors;
    }
    
  2. Add Rule Providers Extend the bundle’s rule providers for custom rules:

    use Assoconnect\GraphQLMutationValidatorBundle\Validator\RuleProviderInterface;
    
    class CustomRuleProvider implements RuleProviderInterface
    {
        public function register(): void
        {
            Validator::extend('custom_rule', function ($attribute, $value, $parameters) {
                return $value === $parameters[0];
            });
        }
    }
    
  3. Localization Override getMessages() for multi-language support:

    protected function getMessages(): array
    {
        return [
            'email.required' => trans('validation.required', ['attribute' => 'Email']),
        ];
    }
    
  4. Symfony/Laravel Hybrid Use the laravel-bundle to share Laravel’s validation pipeline:

    use Assoconnect\GraphQLMutationValidatorBundle\Validator\LaravelValidator;
    
    class UserValidator extends LaravelValidator
    {
        protected function rules(): array
        {
            return [
                'email' => 'required|email',
            ];
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle
cgv/localized-resource