2017-10-21 131 views
3

如何通过身份验证laravel验证阵列名称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]为空,它会返回错误偏移1,这不是知道如何工作了这一点

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


    ] 
+0

为了最佳实践,我建议使用“表单请求验证”https://laravel.com/docs/5.5/validation# form-request-validation –

+0

谢谢你,先生,我会检查它 – test1321

+0

我已经把这种方法的例子作为第二个答案,以防你或别人可能想要在某个时候使用它。 –

回答

3

好吧,既然你在证实$ request变量,您应该验证输入名称。

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

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

无论如何改变由ID验证?是因为它可以是quantity_box [10]我知道有多少用户会插入数据 – test1321

+0

@ test1321是的,有一种方法。 –

+0

可否给我举个例子请@LarsMertens – test1321

1

最佳做法,我建议用Laravel的5.5形式请求验证laravel.com/docs/5.5/validation#form-request-validation

工作使用这种方式,您将让您的控制器代码尽可能干净。


首先让我们请求我们的验证和认证规则myQuantiyBoxRequest.php存储在

php artisan make:request myQuantityBoxRequest 

<?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' 
     ]; 
    } 
} 

精读troller功能示例

use App\Http\Requests\myQuantityBoxRequest; 

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

你走了。如果您使用此功能,它将验证输入,就好像您正在使用$this->validate()

+0

谢谢先生,这让我更懂谢谢了很多先生 – test1321

+0

不客气。 –