Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validate at least one item in a form array

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?

like image 302
Miguel Stevens Avatar asked Aug 18 '17 13:08

Miguel Stevens


People also ask

How do I validate an array in laravel?

you can call validate() method directly on Request object like so: $data = $request->validate([ "name" => "required|array|min:3", "name. *" => "required|string|distinct|min:3", ]); Hope it helps!!

What is bail rule in laravel?

If you added more then one validation on your field like required, integer, min and max then if first is fail then other should stop to display error message. right now by default it print other too. so you can prevent that by using bail validation rule in laravel.

What is the method used to configure validation rules in form request laravel?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


1 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.

like image 122
Hakan SONMEZ Avatar answered Oct 28 '22 00:10

Hakan SONMEZ