Laravel validate at least one item in a form array Laravel validate at least one item in a form array laravel laravel

Laravel validate at least one item in a form array


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.


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