Skip to content

Conversation

lucasmichot
Copy link
Contributor

@lucasmichot lucasmichot commented Sep 3, 2025

Description

This PR adds a json_schema validation rule to Laravel’s validator, allowing attributes to be validated against JSON Schemas. It introduces a new JsonSchema rule class, integrates with opis/json-schema, and includes a fluent Rule::jsonSchema() helper.

This is made possible by he introduction of illuminate/json-schema, see #56903 by @nunomaduro

This is still very much Work in progress.


What's Changed

  • Added validateJsonSchema() method in ValidatesAttributes.
  • Added Rule::jsonSchema(Type $schema) convenience method.
  • New Illuminate\Validation\Rules\JsonSchema class with support for normalization, malformed JSON detection, and detailed error messages.
  • Added opis/json-schema dependency.
  • Test coverage for valid/invalid payloads, malformed JSON, nested schemas, arrays, enums, and required fields.

Motivation

  • Native JSON Schema validation in Laravel.
  • Accurate, schema-based validation with clear error messages.

Example

use Illuminate\Validation\Rule;
use Illuminate\JsonSchema\Types\Type;

$schema = Type::object([
    'name' => Type::string()->required(),
    'age'  => Type::integer()->min(0),
]);

$request->validate([
    'data' => [Rule::jsonSchema($schema)],
]);

Copy link

github-actions bot commented Sep 3, 2025

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@lucasmichot lucasmichot changed the title [12.x ]Introduce as JsonSchema validation rule [12.x ]Introduce a JsonSchema validation rule Sep 3, 2025
@lucasmichot lucasmichot force-pushed the feat/12x-jsonschema-validation branch from 0eb1d26 to 8ed68ce Compare September 4, 2025 08:39
@AhmedAlaa4611
Copy link
Contributor

Hello @lucasmichot

Would it make sense to pass a plain array instead, and let Rule::jsonSchema() internally wrap it in Type::object()? For example:

use Illuminate\Validation\Rule;
use Illuminate\JsonSchema\Types\Type;

$schema = [
    'name' => Type::string()->required(),
    'age'  => Type::integer()->min(0),
];

$request->validate([
    'data' => [Rule::jsonSchema($schema)],
]);

I think we could simply do this by modifying the jsonSchema() method inside src/Illuminate/Validation/Rule.php to be like this:

/**
 * Create a JSON Schema validation rule.
 *
 * @param  array<string, \Illuminate\JsonSchema\Types\Type>  $schema
 * @return \Illuminate\Validation\Rules\JsonSchema
 */
public static function jsonSchema(array $schema)
{
    return new JsonSchemaRule(Type::object($schema));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants