Laravel validate at least one item in a form array

后端 未结 8 1082
借酒劲吻你
借酒劲吻你 2020-12-30 11:12

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




        
8条回答
  •  情书的邮戳
    2020-12-30 11:51

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

提交回复
热议问题