I'm validating question and answers (for test creation). I'd like to ensure that the answers array contains at least one 'correct' item. So where answers.*.correct => true
.
I currently have the following:
public function rules()
{
return [
'title' => 'required|string|max:255',
'test_id' => 'required|integer|exists:tests,id',
'content' => 'required',
'answers' => 'required|array',
'answers.*.text' => 'required|string|max:255',
'answers.*.correct' => 'required|boolean'
];
}
At the moment i can miss out adding a correct answer causing an impossible question.
I've checked the documentation and can't see anything that stands out.
Any help would be appreciated.
EDIT ANSWER
I used this (as the answer mentions): Laravel validate at least one item in a form array
I managed to create a custom rule like so:
public function passes($attribute, $value)
{
foreach ($value as $arrayElement) {
if ($arrayElement['correct'] == true) {
return true;
}
}
return false;
}
Then in my existing rules() section for the request I added in the new rule i created:
'answers' => ['required', 'array', new ArrayAtLeastOneBoolTrue()],