2015-09-15 86 views
0

在我的應用程序管理員可以添加categoriessubcategories。每個category/subcategory具有id,nameslug。然後用戶可以添加article並選擇是否要將category和/或subcategory添加到該用戶。laravel 5.1表單驗證與foreach

這是通過像這樣

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

回答

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/