sadovojav/laravel-json-schema-request

类似于 FormRequests,但用于验证 JSON 模式

1.0.0 2020-06-18 22:56 UTC

This package is auto-updated.

Last update: 2024-09-09 00:32:15 UTC


README

CI Action Code Coverage Scrutinizer Code Quality

Laravel 的 JSON Schema 文档的表单请求验证

安装

 composer require sadovojav/laravel-json-schema-request

使用

开发体验与 Laravel 的表单请求验证相同,但您需要编写的是 JSON Schema 而不是 Laravel 验证规则。

您可以使用 make:json-request 命令创建新的请求

artisan make:json-request MyJsonRequest

现在您将有一个新的请求类 App\Http\Requests\MyJsonRequest,下面是一个基本示例模式。

<?php

namespace App\Http\Requests;

use Webtools\JsonSchemaRequest\JsonSchemaRequest;

class MyJsonRequest extends JsonSchemaRequest
{
    public function schema(): array
    {
        return [
            'type' => 'object',
            'properties' => [
                'first_name' => ['type' => 'string'],
                'last_name' => ['type' => 'string'],
                'email' => ['type' => 'string', 'format' => 'email'],
            ],
            'required' => ['first_name', 'last_name', 'email'],
            'additionalProperties' => false,
        ];
    }
}

一旦您有了 JsonSchemaRequest 对象,您只需在控制器方法中类型提示请求即可。在调用控制器方法之前,会验证传入的表单请求。

public function store(MyJsonRequest $request)
{
    // The incoming request is valid...

    // Retrieve the validated input data...
    $validated = $request->validated();
}

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件