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

Json Schema Laravel Package

justinrainbow/json-schema

Validate JSON documents against JSON Schema in PHP. Supports Draft-3, Draft-4, Draft-6 and Draft-7 (coverage varies). Install via Composer and use JsonSchema\Validator to validate data with local file $ref schemas and inspect validation errors.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Schema Validation Layer: Fits seamlessly into Laravel’s request/response pipeline (e.g., middleware, form requests, API gateways) to enforce structured data contracts.
  • API Contracts: Ideal for validating incoming API payloads (e.g., JSON:API, GraphQL inputs) or database mutations (e.g., Eloquent model attributes).
  • Event/Command Validation: Useful for validating domain events or CQRS commands before processing.
  • Configuration Validation: Can validate app/config files (e.g., config/*.php) or environment variables (via json_decode).
  • Legacy System Integration: Bridges older PHP systems lacking strict typing with modern schema-driven validation.

Integration Feasibility

  • Laravel Service Provider: Can be bootstrapped in register() to preload schemas (e.g., from config/schema.json) and inject a Validator instance into the container.
  • Form Requests: Extend Illuminate\Foundation\Http\FormRequest to validate $request->all() against a schema.
  • API Gateways: Use middleware to validate incoming requests (e.g., validate(Request $request, string $schemaPath)).
  • Eloquent Observers: Validate model attributes before save()/update() via observes([Model::class]).
  • Artisan Commands: Validate CLI input (e.g., --json flags) during command execution.

Technical Risk

  • Draft Compatibility: Risk of partial Draft-7 support; test thoroughly if using advanced features (e.g., $dynamicRef, contentMediaType).
  • Performance Overhead: Schema validation adds latency; benchmark for high-throughput APIs (consider caching compiled schemas).
  • Type Coercion Side Effects: CHECK_MODE_COERCE_TYPES modifies input data; ensure this aligns with business logic (e.g., API responses vs. internal processing).
  • Schema Storage: Remote schemas (e.g., $ref: "https://...") introduce network dependencies; mock or stub for offline testing.
  • PHP Version: Supports PHP 8.1+; ensure compatibility with Laravel’s minimum version (e.g., 8.0+).

Key Questions

  1. Schema Source: Will schemas be:
    • Hardcoded (e.g., resources/schemas/),
    • Dynamically loaded (e.g., from a database),
    • Or fetched remotely (e.g., OpenAPI/Swagger specs)?
  2. Validation Granularity: Should validation occur:
    • Per-request (e.g., API middleware),
    • Per-operation (e.g., command handlers),
    • Or asynchronously (e.g., message queues)?
  3. Error Handling: How should validation errors be surfaced?
    • HTTP responses (e.g., 400 Bad Request with detailed errors),
    • Logs,
    • Or custom exceptions?
  4. Schema Evolution: How will schemas be versioned/updated?
    • Backward-compatible changes only,
    • Or with migration scripts for breaking changes?
  5. Testing Strategy: Will tests validate:
    • Only happy paths,
    • Or edge cases (e.g., malformed JSON, circular references)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Requests: Validate Request objects in middleware/form requests.
    • APIs: Integrate with Laravel Sanctum/Passport for OAuth2 token validation.
    • Queues: Validate job payloads before dispatching (e.g., validate($data, $schema) in handle()).
    • Testing: Use JsonSchema\Validator in PHPUnit tests for contract testing.
  • PHP Extensions:
    • Symfony Components: Works alongside Symfony\Component\Validator for hybrid validation.
    • Laminas/Zend: Compatible with legacy Zend Framework apps.
  • Tooling:
    • Laravel Forge/Envoyer: Deploy schema files alongside app code.
    • Laravel Scout: Validate search queries against a schema before execution.

Migration Path

  1. Phase 1: Pilot Validation
    • Start with a single API endpoint or form request.
    • Example: Validate StorePostRequest against posts/schema.json.
    • Use CHECK_MODE_COERCE_TYPES for type safety.
  2. Phase 2: Schema Centralization
    • Consolidate schemas in config/schemas/ or a dedicated SchemaService.
    • Example:
      // app/Providers/SchemaServiceProvider.php
      public function register()
      {
          $this->app->singleton(Validator::class, fn() => new Validator());
          $this->app->bind(SchemaStorage::class, fn() => new SchemaStorage());
      }
      
  3. Phase 3: Full Pipeline Integration
    • Add middleware for global validation:
      // app/Http/Middleware/ValidateSchema.php
      public function handle(Request $request, Closure $next, string $schema)
      {
          $validator = app(Validator::class);
          $validator->validate($request->json()->all(), $this->loadSchema($schema));
          if (!$validator->isValid()) {
              return response()->json(['errors' => $validator->getErrors()], 400);
          }
          return $next($request);
      }
      
    • Route registration:
      Route::middleware(['validate.schema:users/schema.json'])->group(function () {
          Route::post('/users', [UserController::class, 'store']);
      });
      
  4. Phase 4: Advanced Features
    • Implement schema caching (e.g., SchemaStorage with Redis).
    • Add schema validation for responses (e.g., CHECK_MODE_VALIDATE_SCHEMA).
    • Integrate with Laravel Horizon for async validation of queued jobs.

Compatibility

  • Laravel Versions: Compatible with Laravel 8+ (PHP 8.0+). For Laravel 7, use justinrainbow/json-schema:^6.0 with PHP 7.4+.
  • Dependencies:
    • No conflicts with Laravel’s core or popular packages (e.g., laravel/framework, spatie/laravel-activitylog).
    • Avoid ext/json conflicts by ensuring json_decode is used consistently.
  • Schema Formats: Supports Drafts 3–7; prioritize Draft-7 for new projects.

Sequencing

  1. Schema Design: Define schemas before implementation (use JSON Schema Generator).
  2. Validator Setup: Register the package and SchemaStorage in a service provider.
  3. Pilot Integration: Validate one critical endpoint/form.
  4. Error Handling: Implement custom error responses (e.g., App\Exceptions\ValidationException).
  5. Testing: Write contract tests for all schemas (e.g., tests/Feature/SchemaValidationTest).
  6. Monitoring: Log validation failures (e.g., Sentry) to track schema drift.

Operational Impact

Maintenance

  • Schema Updates:
    • Version schemas with semantic versioning (e.g., schemas/v1/user.json).
    • Use CHECK_MODE_STRICT for Draft-6 to enforce schema validity.
  • Dependency Management:
    • Pin justinrainbow/json-schema to a specific version (e.g., ^6.8) in composer.json.
    • Monitor for breaking changes (e.g., Draft-7 deprecations).
  • Tooling:
    • Add a php-cs-fixer rule to enforce schema file formatting.
    • Use roave/security-advisories to track PHP dependency vulnerabilities.

Support

  • Debugging:
    • Leverage getErrors() for detailed validation feedback.
    • Example debug middleware:
      public function handle($request, Closure $next)
      {
          if (app()->environment('local') && $request->has('debug_schema')) {
              $validator = app(Validator::class);
              $validator->validate($request->all(), $this->loadSchema('debug.json'));
              dd($validator->getErrors());
          }
          return $next($request);
      }
      
  • Documentation:
    • Embed schema examples in API docs (e.g., Swagger/OpenAPI).
    • Add a README.md in config/schemas/ explaining each schema’s purpose.
  • Team Training:
    • Conduct workshops on JSON Schema syntax and Laravel integration.
    • Document common pitfalls (e.g., circular references, type coercion).

Scaling

  • Performance:
    • Caching: Cache compiled schemas in Redis/Memcached (e.g., serialize SchemaStorage).
    • Batch Validation: Validate arrays of objects (e.g., bulk API imports) with a loop:
      foreach ($request->json()->all() as $item) {
          $validator->validate($item, $schema);
          if (!$validator->isValid()) {
              return response()->json(['errors' => $validator->getErrors()], 400);
          }
      }
      
    • Async Validation: Offload validation to queues for long-running processes.
  • Distributed Systems:
    • Store schemas in a shared config service (e.g., Consul, etcd) for microservices.
    • Use file:// references for local schemas
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata