Laravel数组验证 [英] Laravel validation for arrays

查看:104
本文介绍了Laravel数组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个要求:

GET http://example.com/test?q[]=1&q[]=2&q[]=3

我有这条路线:

Route::get('test', function(Request $req) {
    $req->validate(['q' => 'array']);
});

我该如何使用Laravel验证器向该数组的每个元素添加其他验证规则?例如,我要检查每个 q 值是否至少为2.

How should I do to add other validation rules to each element of this array using Laravel validator? For example, I want to check that each q value has a minimum of 2.

谢谢您的帮助.

推荐答案

看看有关验证数组.

$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);

您也可以使用请求对象

You can also do this in your controller using the Request object, documentation about validation logic.

public function store(Request $request)
{
  $validatedData = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
  ]);

  // The blog post is valid...
}

当您有很多验证规则并且想要分离应用程序中的逻辑时,还有第三种选择.看看表单请求

There is a third option for when you have a lot of validation rules and want to separate the logic in your application. Take a look at Form Requests

1)创建一个表单请求类

1) Create a Form Request Class

php artisan make:request StoreBlogPost

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

2) Add Rules to the Class, created at the app/Http/Requestsdirectory.

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

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

3) Retrieve the request in your controller, it's already validated.

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

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

这篇关于Laravel数组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆