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 Guard Laravel Package

league/json-guard

Unmaintained JSON Schema validator (draft 4) for PHP. Passes the full Draft 4 test suite, supports custom rule sets, and returns helpful errors with JSON Pointers. Consider opis/json-schema or swaggest/php-json-schema as alternatives.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/json-guard
    

    (Note: While unmaintained, this package remains functional for Laravel projects using Draft 4 JSON Schema.)

  2. Basic Validation:

    use League\JsonGuard\Validator;
    
    $data = json_decode('{"name": "John", "age": 30}');
    $schema = json_decode('{
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "age": {"type": "integer"}
        },
        "required": ["name"]
    }');
    
    $validator = new Validator($data, $schema);
    
  3. Check Validation:

    if ($validator->passes()) {
        // Data is valid
    } else {
        $errors = $validator->errors(); // Array of ValidationError objects
    }
    

First Use Case

Validate API request payloads or form submissions against structured schemas. Example:

$requestData = json_decode($request->getContent());
$validator = new Validator($requestData, $schema);
if ($validator->fails()) {
    return response()->json(['errors' => $validator->errors()], 422);
}

Implementation Patterns

Common Workflows

  1. Request Validation Middleware:

    public function handle($request, Closure $next) {
        $validator = new Validator(json_decode($request->getContent()), $schema);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
        return $next($request);
    }
    
  2. Service Layer Validation:

    public function create(Request $request) {
        $data = json_decode($request->getContent());
        $validator = new Validator($data, $this->schema);
        if ($validator->fails()) {
            throw new \InvalidArgumentException(json_encode($validator->errors()));
        }
        // Proceed with business logic
    }
    
  3. Dynamic Schema Loading:

    $schema = json_decode(file_get_contents("schemas/{$request->route('schema')}.json"));
    $validator = new Validator($data, $schema);
    

Integration Tips

  • Laravel Form Requests: Use JsonGuardValidator trait to integrate with Laravel's validation system.
  • Error Handling: Convert ValidationError objects to Laravel's Validator format for consistency:
    $laravelErrors = collect($validator->errors())
        ->map(fn($error) => [$error->data_path => $error->message])
        ->toArray();
    
  • JSON References: Use league/json-reference for $ref support:
    $dereferencer = League\JsonReference\Dereferencer::draft4();
    $schema = $dereferencer->dereference('http://example.com/schema.json');
    

Gotchas and Tips

Pitfalls

  1. Data Type Mismatch:

    • Issue: json_decode() with true returns arrays, but JsonGuard expects objects.
    • Fix: Always use json_decode($json, false) (default) for object output.
    $data = json_decode('{"key": "value"}'); // Correct
    $data = json_decode('{"key": "value"}', true); // Incorrect for JsonGuard
    
  2. Circular References:

    • Issue: Deeply nested or circular references may hit the default maxDepth (50).
    • Fix: Increase depth if needed:
    $validator->setMaxDepth(100);
    
  3. Schema Validation:

    • Issue: Schemas themselves must be valid. Use the meta-schema to validate:
    $metaSchema = json_decode(file_get_contents('http://json-schema.org/schema'));
    $schemaValidator = new Validator($yourSchema, $metaSchema);
    

Debugging Tips

  • Error Messages: Use data_path and schema_path in ValidationError to pinpoint issues in nested structures.
  • Custom Rules: Extend the DraftFour ruleset for custom validation logic:
    $validator->getRuleset()->get('customKeyword')->addConstraint(new CustomConstraint());
    
  • Performance: Dereference schemas once and reuse them (cache the dereferenced schema).

Extension Points

  1. Custom Formats:
    $validator->getRuleset()->get('format')->addExtension('custom-format', new CustomFormatExtension());
    
  2. Custom Constraints:
    $validator->getRuleset()->add('customKeyword', new CustomConstraint());
    
  3. Error Handling: Override ValidationError or use middleware to transform errors into API-friendly responses.

Laravel-Specific Quirks

  • Service Provider: Register a singleton validator for reuse:
    $this->app->singleton(Validator::class, function () {
        return new Validator(json_decode('{}'), json_decode('{}'));
    });
    
  • Validation Exceptions: Catch MaximumDepthExceededException for recursive data:
    try {
        $validator->validate();
    } catch (\League\JsonGuard\Exception\MaximumDepthExceededException $e) {
        // Handle circular reference
    }
    
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