laravel 如何将自定义数组或自定义请求传递给FormRequest?

uqcuzwp8  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(250)

我需要动态创建一个自定义请求,并将请求传递给Form Request。我找到的最接近的答案是this SO answer。但是,当我运行$request->validated()时,它给我错误消息Call to a member function validated() on null in /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:221
下面是完整的代码:
功能A

private $service;

public function __construct(
    Service $service,
) {
    $this->service = $service;
}

...

$data = [
    "variable_a" => "string",
    'variable_b' => true,
];
$request = new Request();
$request->replace($data);
$customFormRequest = new CustomFormRequest();
$validate = $customFormRequest::createFrom(
    $request
);
$return_data = $this->service->project($validate);

服务

public function project(CustomFormRequest $request)
{
    \Log::debug($request);
    $data = $request->validated();
    \Log::debug($data);
}

注意在服务内部登录时,$request$request->all()具有数组值

vlju58qv

vlju58qv1#

它不起作用的原因是因为您只获取了CustomFormRequest的一个示例。自定义窗体请求只有在容器外解析时才被验证。请改用验证程序:

class SomeClass
{
    public function __construct(private Service $service) {}

    public function call()
    {
        $data = [
            'variable_a' => 'string',
            'variable_b' => true,
        ];

        $validator = \Illuminate\Support\Facades\Validator::make(
            $data,
            [
                'variable_a' => 'required|string',
                'variable_b' => 'required|boolean',
            ]
        );

        // You'll probably want to check $validator->passes() / $validator->fails()
        // before moving on.

        $return_data = $this->service->project($validator->validated());
    }
}

我假设此时没有理由将CustomFormRequest的示例传递给project(),因为数据已经过验证。只需更新类型:

public function project(array $request)
    {
        // do whatever you need to do with the array
    }

相关问题