I am searching for a improvement to this Laravel FormRequest rule set:
protected $stopOnFirstFailure = true;
public function rules()
{
return [
'reasons' => ['required', 'array'],
'reasons.*.id' => ['exists:reject_reasons,id'],
'reasons.*.text' => Rule::forEach(function ($value, $attribute, $data) {
// get the key from the array attribute
list(, $key) = explode('.', $attribute);
$reason = RejectReason::find($this->reasons[$key]['id']);
return [
Rule::requiredIf(optional($reason)->with_additional_entry),
'max:255'
];
}),
];
}
The .text element should only be required and checked if the id element exists in the database and the attribute with_additional_entry is true.
Things that could be improved:
- If the id is not in the database the validator does not stop after the
reasons.*.idrule, so I have to check for the$reasonObject -> optional() - Get the key of the form array
list(, $key) = explode('.', $attribute);
Does anyone have a better solution to this?