使用foreach进行laravel 5.1表单验证

时间:2015-09-15 12:03:52

标签: php validation laravel-5.1

在我的应用管理员中,可以添加categoriessubcategories。每个category/subcategory都有idnameslug。然后,用户可以添加article并选择是否要向该用户添加category和/或subcategory

这是通过看起来像这样的输入表单来完成的。

O - Add category 1 subcategories
O - Add category 2 subcategories

其中O是复选框。点击O - add category x subcategories将打开子类别列表:

O - Add category 1 subcategories
 ----O - 1st subcat
 ----O - 2nd subcat
 ----O - 3rd subcat
O - Add category 2 subcategories
 ----O - 1st subcat
 ----O - 2nd subcat
 ----O - 3rd subcat

输入ID为category1slug[subcategory1slug]category1slug[subcategory2slug],依此类推。它们以foreach循环

的形式呈现
foreach ( $categories as $category) { input field }

现在我想验证这些条目如下。如果选择了O - Add category 1 subcategories字段,我希望至少选择一个子类别。我所做的自定义验证在这里:

Laravel 5.1, nested validation

但是,我不知道如何将其应用于所有类别。我希望得到如下验证:

'category1slug' => 'required_with_one_of:category1slug.subcategory1slug,category1slug.subcategory2slug,category1slug.subcategory3slug',
'category2slug' => 'required_with_one_of:category2slug.subcategory3slug,category2slug.subcategory4slug,category2slug.subcategory5slug',
'category3slug' => 'required_with_one_of:category3slug.subcategory6slug,category3slug.subcategory7slug,category3slug.subcategory8slug',

但我不想每次都手动添加它们,因为数据已经存在于数据库中。此外,如果我必须手动添加它们,每次管理员添加新类别或子类别或更改子类别/类别关系时,我都必须下降到routes.php

1 个答案:

答案 0 :(得分:0)

Request文件中有

public function rules()
{ 
  return [];
}

返回数组。将数组返回为:

public function rules()
{ 
  $therulesarray = [];

  foreach ( $categories as $category) { 
    //desired logic here
    $therulesarray['attribute'] = 'rulestoapply'; //this will add new element in $therulesarray that our function rules() returns;
  }
  return $therulesarray;
}

更多信息:http://ericlbarnes.com/laravel-array-validation/