php - Laravel 4 Validation - Nested Indexed Arrays? -
i have array of various things...
$foo = []; $foo['stuff']['item'][0]['title' => 'flying_lotus']; $foo['stuff']['item'][1]['title' => 'various_cheeses']; $foo['stuff']['item'][2]['title' => 'the_career_of_vanilla_ice']; $foo['stuff']['item'][3]['title' => 'welsh_cats'];
how validate 'title' key, using validator method in laravel 4?
here's have far...
$validator = validator::make($foo, ['stuff.item.???.title' => 'required']);
i'm totally flummoxed indexed array. great .
the following answer laravel <= 5.1. laravel 5.2 introduced built-in array validation.
at time, validator class isn't meant iterate on array data. while can traverse through nested array find specific value, expects value single (typically string
) value.
the way see it, have few options:
1: create rules array key in field name.
basically you're doing already, except you'd need figure out how many values ['stuff']['item']
array has. did results:
$data = [ 'stuff' => [ 'item' => [ ['title' => 'flying_lotus'], ['title' => 'various_cheeses'], ['title' => ''], ['title' => 'welsh_cats'], ] ] ]; $rules = []; ($i = 0, $c = count($data['stuff']['item']); $i < $c; $i++) { $rules["stuff.item.{$i}.title"] = 'required'; } $v = validator::make($data, $rules); var_dump($v->passes());
2: create custom validation method.
this allow create own rule, can expect array value , iterate on necessary.
this method has caveats, in a) won't have specific value error messages, since it'll error entire array (such if pass stuff.item
value check), , b) you'll need check of array's possible values in custom function (i'm assuming you'll have more title
validate).
you can create validation method using validator::extend()
or extending class somewhere else.
3: extend validator class , replace/parent rules in question accept arrays.
create own extended validator class, , either implement custom rules, or rename existing ones, enabling rules accept array value if 1 happens along. has similar caveats #2 custom rule option, may "best practice" if intend on validating iterated arrays often.
Comments
Post a Comment