only get validated data from laravel validator

时间:2018-06-19 11:14:18

标签: php laravel validation

When validating data with the validator, it's possible to get all processed data from the validator using the getData() method. However, that returns all data that has been passed into the validator. I only want the data that actually fit the validation pattern.

For example:

$data = [
    'email'          => email@example.com,
    'unnecessaryKey' => 'whatever'
];

$validator = Validator::make($data, [
        'email'       => 'required|string',
]);

$validator->getData()

Would return the "unnecessaryKey" as well as the email. The question is: Is it possible to only return the email in this case, even though i passed in unnecessaryKey as well?

2 个答案:

答案 0 :(得分:4)

如果您从$ request获取数据,则可以尝试

{
"metrics": [
{
  "tags": {},
  "name": "test4",
  "aggregators": [
    {
      "name": "sum",
      "sampling": {
        "value": "1",
        "unit": "milliseconds"
      }
    }
  ]
}
],
"plugins": [],
"cache_time": 0,
"start_absolute": 1529346600000
}

如果您要验证$ data数组,则可以尝试

$validator = Validator::make($request->only('email') , [
        'email'       => 'required|string',
]);

希望这会有所帮助。

答案 1 :(得分:1)

为此,您应该使用Form Requests

1)创建一个表单请求类

php artisan make:request StoreBlogPost

2)将规则添加到在app / Http / Requests目录中创建的类。

public function rules()
{
  return [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
  ];
}

3)在控制器中检索该请求,该请求已被验证。

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

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