I have a form with a series of numbers in an array:
'items' => 'required|array', // validate that field must be from array type and at least has one value
'items.*' => 'integer' // validate that every element in that array must be from integer type
and you can add any other validation rules for those elements like: 'items.*' => 'integer|min:0|max:100'
You can set your rules for array and foreach elements.
public function rulez(Request $req) {
$v = Validator::make($req->all(), [
'items' => 'required|array|min:1',
'items.*' => 'required|integer|between:0,10'
]);
if ($v->fails())
return $v->errors()->all();
}
First rule say that items must be an array with 1 element at least. Second rule say that each elements of items must be an integer between 0 and 10.
If the rules seem not to work, try to dump your $req->all().
dump($req->all());
In addition ot Hakan SONMEZ's answer, to check if at least one array element is set, the Rule object can be used. For example create rule class and name it ArrayAtLeastOneRequired().
To create new rule class run console command:
php artisan make:rule ArrayAtLeastOneRequired
Then in created class edit method passes():
public function passes($attribute, $value)
{
foreach ($value as $arrayElement) {
if (isset($arrayElement)) {
return true;
}
}
return false;
}
Use this rule to check if at least one element of array is not null:
Validator::make($request->all(), [
'array.*' => [new ArrayAtLeastOneRequired()],
]);
$this->validate($request,[
'item'=>'required|min:1'
]);
The accepted answer is ok, and it is working fine, but if you don't want to create function and other stuff then the another workaround which i have used is
that you can directly state the element of array as items.0
and make that input required, it will not care about other inputs but it will make first input required, it is not usable in all the cases but in my case it is useful.
in your OrderCreateRequest
:
public function rules()
{
return [
"items.0" => "required",
];
}
And if your items are not dynamic and not in very large amount then you can use required_without_all
as below:
public function rules()
{
return [
"items.0" => "required_without_all:items.1,items.2",
"items.1" => "required_without_all:items.0,items.2",
"items.2" => "required_without_all:items.0,items.1",
];
}
If you are using this in your controller file then I guess it should be
$this->validate($request, [
'items' => 'required|min:1'
]);
or this one
$validator = Validator::make($request->all(), [
"items.*" => 'required|min:1',
]);
you can refer How to validate array in Laravel? to this as well.