JsonSchema Validate For Laravel Request And Response
composer require kojirock5260/laravel-json-schema-validate
php artisan vendor:publish --provider=Kojirock5260\\JsonSchemaValidate\\JsonSchemaServiceProvider
Please describe
protected $routeMiddleware = [
...
'json_schema' => \Kojirock5260\JsonSchemaValidate\Middleware\JsonSchemaValidator::class,
];
<?php
Route::group(['middleware' => ['json_schema']], function () {
Route::get('/member', 'MemberController@index')->name('MemberList');
});
- Be sure to set the route name
- App\Http\Schema\Request\{RouteName}.php
- 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'
],
],
];
}
}
- 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);
}
- config/json-schema.php
<?php
return [
/**
* Schema Directory Base Namespace
*/
'namespace' => 'Acme\\Member\\Schema',
];
The MIT License (MIT). Please see License File for more information.