Home » Php » php – Laravel validate at least one item in a form array

php – Laravel validate at least one item in a form array

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.

Answer:

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()],
 ]);

Answer:

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.

Answer:

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",
   ];
}

Answer:

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());

Answer:

$valid = Validator($request->all(), [
    'type' => 'required|string|in:city,region,country',
]);

if ($valid->fails()) return response()->json($valid->errors(), 400);

Answer:

$this->validate($request,[
'item'=>'required|min:1'

]);

Answer:

'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'