在数组名称 Laravel 中验证

Validate in array name Laravel

如何通过 Id 验证 laravel

现在我在我的控制器中使用它。我的问题是在我的 html 我的输入类型文本是这样的

<input type="text" name="quantity_box[]" class="form-control" autofocus="" />
<input type="text" name="quantity_box[1]" class="form-control" autofocus="" />
<input type="text" name="quantity_box[2]" class="form-control" autofocus="" />

好吧,正如您在我的 html 中看到的那样,如果我的 quantity_box[1] 为空,它将仅检查我的第一个输入,它将 return 错误偏移量 1 ,这不确定如何工作出来

 $this->validate($request, [
        'id_p' => 'required',
        'id_c' => 'required',
        'quantity_box'=>'required',


    ]

好吧,既然您要验证 $request 变量,那么您应该验证输入名称。

如果您使用 Laravel 5.2+ ,您可以像这样验证数组。

 $validator = Validator::make($request->all(), [
        'quantity_box.*' => 'required',
     ]);

为了获得最佳实践,我建议使用 Laravel 的 5.5 表单请求验证 laravel.com/docs/5.5/validation#form-request-validation

使用这种方式,您将保持控制器代码尽可能干净。


首先让我们发出一个请求,将我们的验证和身份验证规则存储在

php artisan make:request myQuantityBoxRequest

myQuantiyBoxRequest.php

<?php 

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Auth;

class myQuantityBoxRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * The user is always authorized here to make the request
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'quantity_box.*' => 'required'
        ];
    }
}

控制器函数示例

use App\Http\Requests\myQuantityBoxRequest;

public function postQuantityBoxData(myQuantityBoxRequest $request){
     // Do something after validation here
}

给你。如果您使用此功能,它将像您使用 $this->validate()

一样验证输入