Laravel validate at least one item in a form array
Asked Answered
Y

8

16

I have a form with a series of numbers in an array:

<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />
<input type="number" name="items[{{ $sku }}]" min="0" />

I would like to validate that there is at least one of those input fields that has a value.

I tried the following in my OrderCreateRequest, yet the test is passing:

return [
    'items' => 'required|array|min:1'
];

Am I missing something?

Yahiya answered 18/8, 2017 at 13:55 Comment(0)
T
17

I think you need a custom validation rule like the following because min is not for the elements of the array.

Validator::extend('check_array', function ($attribute, $value, $parameters, $validator) {
     return count(array_filter($value, function($var) use ($parameters) { return ( $var && $var >= $parameters[0]); }));
});

You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.

App\Providers\ValidatorServiceProvider::class,

Or you just add them top of the action of your controller.

At the end you can use it like this in your validation rules.

'items' => 'check_array:1',

Note: if I understand you correctly it works.

Tin answered 18/8, 2017 at 14:27 Comment(5)
Great solution! Thank you.Yahiya
dont forget to add 'check_array' => 'at least one item is required', to langs/*/validation.phpScurvy
for some reason this now always return 0 check sandbox.onlinephpfunctions.com/code/…Scurvy
Your code has some logical errors. so you should try like this sandbox.onlinephpfunctions.com/code/…Tin
The string value of a date 01/08/2021 fails the validator (php 7.4.8) since the parameter is a string and the slash breaks the behavior, I would use !empty($var) insteadClassroom
A
11

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 (null !== $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()],
 ]);
Aldose answered 15/12, 2018 at 9:40 Comment(2)
Great answer! Please note the validation rule should be applied to the array 'array' and not to the array element 'array.*' otherwise the foreach loop won't be able to iterate .Gharry
This is precisely what I was looking for. Thank you!Intermixture
F
5

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.

Frigg answered 18/8, 2017 at 14:36 Comment(3)
second example with items.* will check that all values in items array should have at-least 1 character in it, but here we have to validate to minimum 1 element should be there in array so, first example is right but second one is wrong because it will check values.Fortyish
First example is wrong as well because it would pass an array with a single null value. This answer doesn't address the question and shouldn't be upvoted.Gharry
Not correct . i tried itUnhesitating
F
4

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",
   ];
}
Fortyish answered 25/7, 2019 at 11:19 Comment(0)
O
-1

"size" rule is used to match exact no. of items in array (if incoming parameter is an array) and same goes for "min" rule i.e it count minimum no. of elements in an array (if incoming parameter is an array)

$this->validate($request, ['my_array' => 'size:6']); // array must have 6 items

$this->validate($request, ['my_array' => 'min:1']); // there must be 1 item in array

https://laravel.com/docs/8.x/validation#rule-size

Obedient answered 24/4, 2021 at 12:1 Comment(0)
B
-2
'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'

Bichromate answered 10/7, 2018 at 10:34 Comment(2)
the min attribute has nothing to do with the count items, instead it checks the value itselfMalformation
@Malformation and that what i meant to check the elements. * here it means apply the rules on every element in this array. not checking the countBichromate
C
-3

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());
Charismatic answered 18/8, 2017 at 14:3 Comment(4)
that means all elements of input array are required and they can be minimum 1. He wants a validation rule which makes at least one element of array is required and others are optional.Tin
ok, you can use 'items' => 'required|array|min:1' Are you sure to receive the Request parameters correctly?Charismatic
Please add a short explanation.Culicid
I am not the one asked the question.Tin
A
-3
$valid = Validator($request->all(), [
    'type' => 'required|string|in:city,region,country',
]);

if ($valid->fails()) return response()->json($valid->errors(), 400);
Abdu answered 3/4, 2020 at 7:49 Comment(3)
a verbal explanation is often helpfulGlue
This answer is incorrect and doesn't answer the question.Gharry
Incorrect answer.Underweight

© 2022 - 2024 — McMap. All rights reserved.