In my app administrator can add categories
, and subcategories
. Each category/subcategory
has an id
, name
and slug
. Then the user can add an article
and select if she wants to add a category
and/or subcategory
to that user.
This is done through input forms which looks like this
O - Add category 1 subcategories
O - Add category 2 subcategories
Where O are checkboxes. Clicking on O - add category x subcategories
will open list of subcategories as:
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
input id's are as category1slug[subcategory1slug]
, category1slug[subcategory2slug]
, and so on. They are rendered in a form with foreach
loop as
foreach ( $categories as $category) { input field }
Now I want to validate these entries as follows. If O - Add category 1 subcategories
field is selected I want at least one of the subcategories to be selected. The custom validation I have done is here:
Laravel 5.1, nested validation
However I don't know how to apply it to all of the categories. I want to get the validation as follows:
'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',
but I don't want to have to add them manually every time since the data is already in the database. Also if I had to add them manually I would have to descend to routes.php
every time an admin adds new category or subcategory or when he changes subcategory/category relation.
in Request
file there is
public function rules()
{
return [];
}
which returns array. Return array as:
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;
}
Some more info: http://ericlbarnes.com/laravel-array-validation/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.