Laravel validator with pattern

I want to make a laravel validator that checks the fields inside an unnamed array (0,1,2,3) which is inside the array

so my array is like

array [ //the form data "items" => array:2 [ //the main array i want to validate 0 => array:2 [ // the inner array that i want to validate its data "id" => "1" "quantity" => "1000" ] 1 => array:2 [ "id" => "1" "quantity" => "1000" ] // other fields of the form, ] ] 

so i want something like

  $validator = Validator::make($request->all(), [ 'items.*.id' => 'required' //notice the star * ]); 
+5
source share
2 answers

Laravel 5.2

Question syntax is now supported

http://laravel.com/docs/master/validation#validating-arrays

Laravel 5.1

First create a validator with all your other rules. Use the array rule for elements

 $validator = Validator::make($request->all(), [ 'items' => 'array', // your other rules here ]); 

Then use the Validator each method to apply a set of rules to each item in the items array.

 $validator->each('items', [ 'id' => 'required', 'quantity' => 'min:0', ]); 

This will automatically set these rules for you ...

 items.*.id => required items.*.quantity => min:0 

https://github.com/laravel/framework/blob/5.1/src/Illuminate/Validation/Validator.php#L261

+5
source

You could just do something like this:

  $rules = []; for($i = 0; $i < 10; $i++) { $rules["items.$i.id"] = "required"; } $validator = \Validator::make($request->all(), $rules); 
0
source

Source: https://habr.com/ru/post/1234609/


All Articles