Weave Code
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

Validator Laravel Package

draw/validator

PHP validation library providing a fluent API to define rules, validate arrays/inputs, and collect errors. Lightweight and framework-agnostic, suitable for Laravel or standalone apps.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Modular Validation Layer: The package leverages Symfony’s Validator component, offering a structured way to enforce validation rules declaratively (via annotations, YAML, or XML). This aligns well with Laravel’s growing adoption of Symfony components (e.g., HTTP client, UX) and provides a centralized validation layer for complex business rules.
  • Symfony-Laravel Synergy: While Laravel’s built-in Validator facade suffices for simple cases, this package introduces Symfony’s constraint system (e.g., @Assert\Callback, @Assert\Expression), which is invaluable for:
    • Domain-driven validation (e.g., "order total must match payment gateway").
    • Reusable validation pipelines (e.g., shared constraints across microservices).
  • Abstraction Overhead: The package adds a Symfony dependency, which may conflict with Laravel’s existing validation tools (e.g., Form Requests, API Resources). If the team already uses Laravel’s Rule objects or Validator facade extensively, the marginal benefit may not justify the complexity.

Integration Feasibility

  • Dependency Conflicts: The package requires Symfony’s validator (v6.4+) and dependency-injection components. Laravel apps using older Symfony versions (e.g., v5.x) or other Symfony packages (e.g., symfony/console) may face:
    • Version mismatches: Resolve via composer.json overrides or Laravel’s extra:laravel config.
    • Container collisions: Symfony’s ValidatorInterface may conflict with Laravel’s service container bindings.
  • Laravel Ecosystem Compatibility:
    • Form Requests: Can replace validate() with Symfony’s constraints, but requires custom error mapping to Laravel’s ValidationException.
    • API Resources: Symfony’s ConstraintViolation objects must be translated to Laravel’s error formats (e.g., JSON responses in Sanctum/Nova).
    • Testing: The package’s phpunit dependency may introduce conflicts with Laravel’s testing setup (e.g., Tests\TestCase vs. Symfony’s Test\WebTestCase).
  • Performance: Symfony’s Validator is heavier than Laravel’s native validator. Benchmark critical paths (e.g., API endpoints) to ensure no latency spikes.

Technical Risk

  • Maintenance Burden: The package’s 0 stars/dependents and lack of recent activity (no commits since 2023) signal:
    • Stagnation risk: Future Symfony v7+ updates may break compatibility without maintainer support.
    • Limited community: Fewer resources for troubleshooting or best practices.
  • Error Handling Complexity: Symfony’s ConstraintViolation objects differ from Laravel’s ValidationException, requiring custom mapping logic to maintain consistency in:
    • API responses (e.g., JSON error formats).
    • Blade templates (e.g., displaying validation errors).
  • Learning Curve: Engineers must familiarize themselves with Symfony’s constraint system (e.g., @Assert\All, @Assert\Valid), which may not align with Laravel’s conventions.

Key Questions

  1. Business Justification:
    • Are we validating complex, reusable rules (e.g., cross-field constraints, dynamic validation) that Laravel’s native tools cannot handle?
    • Does the team have Symfony experience to mitigate the learning curve?
  2. Dependency Impact:
    • What’s the bundle size impact of adding Symfony’s validator + dependency-injection?
    • Will this conflict with existing Symfony components (e.g., symfony/http-foundation)?
  3. Error Handling:
    • How will Symfony’s ConstraintViolation objects map to Laravel’s error responses (e.g., API JSON, Blade errors)?
  4. Testing Strategy:
    • Will the package’s phpunit dependency conflict with Laravel’s testing setup?
    • How will we test custom constraints (e.g., @Assert\Callback)?
  5. Long-Term Viability:
    • Is there a Laravel-native alternative (e.g., spatie/laravel-validation-extensions) that achieves similar goals with lower risk?
    • Can we contribute to the package to ensure it evolves with Symfony/Laravel?

Integration Approach

Stack Fit

  • Ideal Use Cases:
    • Domain-Specific Validation: Enforce complex business rules (e.g., "invoice total must match tax calculations") in a service layer.
    • Microservices: Share validation logic across Laravel and Symfony services using Symfony’s constraint system.
    • Legacy Migration: Gradually introduce structured validation to older Laravel apps lacking robust input sanitization.
  • Misalignment:
    • Simple Validation Needs: If the app only uses basic rules (e.g., required|email), Laravel’s built-in Validator is sufficient.
    • Frontend Integration: For real-time validation (e.g., Vue/React + Laravel), Laravel’s native validation responses may be easier to integrate.
  • Hybrid Strategy:
    • Use draw/validator only for domain logic (e.g., service layer) while keeping Laravel’s validation for HTTP-boundary concerns (e.g., Form Requests).

Migration Path

  1. Pilot Phase:
    • Isolate a Feature: Replace custom validation logic in a single service (e.g., UserRegistrationService) with draw/validator constraints.
    • Test Error Formats: Ensure Symfony’s ConstraintViolation objects map correctly to Laravel’s error responses.
    • Benchmark Performance: Compare against Laravel’s native validator for critical paths.
  2. Incremental Adoption:
    • Phase 1: Custom Validators: Replace ad-hoc validation (e.g., if (!preg_match(...))) with Symfony constraints in services.
      use Draw\Validator\Constraints as Assert;
      
      class Order {
          #[Assert\Callback(fn (Order $order) => $order->total > 0)]
          public float $total;
      }
      
    • Phase 2: Form Requests: Extend FormRequest to use the package’s validator:
      public function validate() {
          $validator = app(\Symfony\Component\Validator\ValidatorInterface::class);
          $violations = $validator->validate($this->all());
          if ($violations->count()) {
              throw new \Illuminate\Validation\ValidationException($this->formatErrors($violations));
          }
      }
      
    • Phase 3: API Resources: Adapt error responses in Nova/Sanctum to include Symfony validation messages.
  3. Dependency Management:
    • Resolve conflicts via composer.json:
      "extra": {
        "laravel": {
          "dont-discover": ["draw/validator"]
        }
      }
      
    • Bind Symfony’s ValidatorInterface to Laravel’s container:
      $this->app->bind(\Symfony\Component\Validator\ValidatorInterface::class, function ($app) {
          return \Symfony\Component\Validator\Validation::createValidatorBuilder()
              ->enableAnnotationReading()
              ->getValidator();
      });
      

Compatibility

  • Service Provider:
    • Register the validator in AppServiceProvider:
      public function register() {
          $this->app->singleton(\Symfony\Component\Validator\ValidatorInterface::class, function ($app) {
              return \Symfony\Component\Validator\Validation::createValidatorBuilder()
                  ->enableAnnotationReading()
                  ->getValidator();
          });
      }
      
  • Facade:
    • Create a Laravel facade to bridge Symfony and Laravel:
      namespace App\Facades;
      
      use Illuminate\Support\Facades\Facade;
      
      class ValidatorFacade extends Facade {
          protected static function getFacadeAccessor() {
              return \Symfony\Component\Validator\ValidatorInterface::class;
          }
      }
      
  • Error Mapping:
    • Transform ConstraintViolation objects to Laravel’s format:
      public function formatErrors(ConstraintViolationListInterface $violations): array {
          return array_reduce($violations, function (array $errors, ConstraintViolationInterface $violation) {
              $errors[$violation->getPropertyPath()][] = $violation->getMessage();
              return $errors;
          }, []);
      }
      

Sequencing

  1. Step 1: Domain Validation
    • Replace custom validation logic in services with Symfony constraints.
    • Example:
      use Draw\Validator\Constraints as Assert;
      
      class Invoice {
          #[Assert\GreaterThan(0)]
          public float $amount;
      
          #[Assert\All([new Assert\Type('string'), new Assert\Length(max: 255)])]
          public string $reference;
      }
      
  2. Step 2: Form Requests
    • Extend FormRequest to use the package:
      public function validate() {
          $validator = app(\Symfony\Component\Validator\ValidatorInterface::class);
          $violations = $validator->validate($this->all());
          if ($violations->count()) {
              throw new \Illuminate\Validation\ValidationException($this->formatErrors($violations));
          }
      }
      
  3. Step 3: API Integration
    • Adapt error responses in Sanctum/Nova to include Symfony validation messages.
    • Example Sanctum response:
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky