简体   繁体   中英

Validate value where another column's value for the record is in array of values

Input to be validated is a tree where a subcategory is valid, only if its' parent category has been selected too.

The input values are as follows:

$categories = [1,2,3];
//in database, each subcategory has column "category_id"
$sub_categories = [4,5,6]

Validation

$this->validate([
 "sub_categories.*" => [
  "exists:sub_categories,id",
  //Rule for checking that the category_id for this subcategory
  //exists in the categories array.
 ]
])

Is there such a built in laravel rule or do I need to write the rule myself?

Use the Rule class

Validation

$this->validate([
    "sub_categories.*" => [
        "exists:sub_categories,id", 
        \Illuminate\Validation\Rule::in($categories),
    ],
])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM