如何在 Laravel 中在没有请求的情况下进行验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49827068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:38:10  来源:igfitidea点击:

How to validate without request in Laravel

phplaravellaravel-5.6

提问by user3743266

I need to validate an array but without a request. In laravel docs validation is described like this:

我需要验证一个数组但没有请求。在 laravel docs 验证是这样描述的:

$validator = Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

But I can't use $request because the data comes from an external api and the validation is not inside a controller. How can I validate this array? For example:

但是我不能使用 $request 因为数据来自外部 api 并且验证不在控制器内部。我如何验证这个数组?例如:

$validatedData = validate([
    'id' => 1,
    'body' => 'text'
], [
    'id' => 'required',
    'body' => 'required'
]);

采纳答案by Amr Aly

You can achieve this by create request object like so:

您可以通过像这样创建请求对象来实现这一点:

$request = new Request([
    'id' => 1,
    'body' => 'text'
]);

$this->validate($request, [
    'id' => 'required',
    'body' => 'required'
]);

and thus you will get all the functionality of the Request class

因此您将获得 Request 类的所有功能

回答by Ariel Pepito

Should be. Because $request->all()hold all input data as an array .

应该。因为$request->all()将所有输入数据保存为一个数组。

$input = [
    'title' => 'testTitle',
    'body' => 'text'
];


$input is your customs array.

$validator = Validator::make($input, [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

回答by Muhammad Nauman

Validator::make expects array and not a request object. You can pass any array and implements the rules on it.

Validator::make 需要数组而不是请求对象。您可以传递任何数组并在其上实现规则。

Validator::make(['name' => 'Tom'], ['name' => 'required', 'id' => 'required']);

And it will validate the array. So $request object is not necessary.

它将验证数组。所以 $request 对象不是必需的。

回答by Anas K

$request->all()is array not request object. This code will work:

$request->all()是数组不是请求对象。此代码将起作用:

$data = [
    'id' => 1,
    'body' => 'text'
];

$validator = Validator::make($data, [
    'id' => 'required',
    'body' => 'required',
]);

回答by omarjebari

You can also merge data with the request object:

您还可以将数据与请求对象合并:

$data = ['id' => 1];
$request->merge($data);

Then validate as per usual.

然后照常验证。