kojirock5260 / laravel-json-schema-validate
json schema for request and response
Installs: 1 063
Dependents: 0
Suggesters: 0
Security: 0
Stars: 5
Watchers: 1
Forks: 4
Open Issues: 0
Requires
- php: ^7.1
- illuminate/http: ^5.8|^6.0|^7.0
- illuminate/routing: ^5.8|^6.0|^7.0
- illuminate/support: ^5.8|^6.0|^7.0
- justinrainbow/json-schema: ^5.2.8
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- laravel/framework: ^5.8|^6.0|^7.0
- phpstan/phpstan: ^0.12.18
This package is auto-updated.
Last update: 2025-04-26 01:45:15 UTC
README
JsonSchema Validate For Laravel Request And Response
Installation
composer require kojirock5260/laravel-json-schema-validate
php artisan vendor:publish --provider=Kojirock5260\\JsonSchemaValidate\\JsonSchemaServiceProvider
Setup
Please describe
1. app/Http/Kernel.php
protected $routeMiddleware = [
...
'json_schema' => \Kojirock5260\JsonSchemaValidate\Middleware\JsonSchemaValidator::class,
];
2. routes/*.php
<?php Route::group(['middleware' => ['json_schema']], function () { Route::get('/member', 'MemberController@index')->name('MemberList'); });
- Be sure to set the route name
3. Schema Files
Path
Request
- App\Http\Schema\Request\{RouteName}.php
Response
- App\Http\Schema\Response\{RouteName}.php
<?php declare(strict_types=1); namespace App\Http\Schema\Request; use Kojirock5260\JsonSchemaValidate\SchemaInterface; class MemberList implements SchemaInterface { public static function getSchema(): array { return [ 'required' => ['page'], 'type' => 'object', 'properties' => [ 'page' => [ 'type' => 'string', 'pattern' => '^([1-9]|[1-9][0-9]*)$', ], 'employment' => [ 'type' => 'string', 'enum' => array_map('strval', array_keys(\App\Models\Member::EMPLOYMENT_LIST)), ], 'department' => [ 'type' => 'string', 'enum' => array_map('strval', array_keys(\App\Models\Member::DEPARTMENT_LIST)), ], 'mailAddress' => [ 'type' => 'string', 'format' => 'email' ], ], ]; } }
4. Exceptions
- App\Exceptions\Handler.php
/** * Prepare exception for rendering. * * @param \Throwable $e * @return \Throwable */ protected function prepareException(Throwable $e) { if ($e instanceof JsonSchemaException) { return ValidationException::withMessages($e->getSchemaErrors()); } return parent::prepareException($e); }
Schema Directory Customise
- config/json-schema.php
<?php return [ /** * Schema Directory Base Namespace */ 'namespace' => 'Acme\\Member\\Schema', ];
License
The MIT License (MIT). Please see License File for more information.