Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

php - Laravel validator with a wildcard

i want to make a laravel validator that validates the the fields inside an un-named array ( 0,1,2,3 ) that is inside an 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 what i want is something like

  $validator = Validator::make($request->all(), [
     'items.*.id' => 'required' //notice the star *
  ]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Laravel 5.2

The syntax in the question is now supported

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

Laravel 5.1

First create the validator with all of your other rules. Use the array rule for items

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

Then use the Validator each method to apply a set of rules to every 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...