I am a beginnerwith the Laravel framework. I am struggling to declare validation of request data. I have some checkboxes in the form, and at least one of the checkboxes must be selected to submit to the database.
<input type="hidden" name="has_a_type" value="0">
<input type="checkbox" name="has_a_type" value="1">
<input type="hidden" name="has_b_type" value="0">
<input type="checkbox" name="has_b_type" value="1">
<input type="hidden" name="has_c_type" value="0">
<input type="checkbox" name="has_c_type" value="1">
<input type="hidden" name="has_d_type" value="0">
<input type="checkbox" name="has_d_type" value="1">
<input type="hidden" name="has_e_type" value="0">
<input type="checkbox" name="has_e_type" value="1">
<input type="hidden" name="has_f_type" value="0">
<input type="checkbox" name="has_f_type" value="1">
public function store(Request $request) {
$request = $request->validate([
'form_id' => 'required',
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
'has_a_type' => 'required',
'has_b_type' => 'required',
'has_c_type' => 'required',
'has_d_type' => 'required',
'has_e_type' => 'required',
'has_f_type' => 'required',
]);
}
When users submit the form, they must select the form type at least once. How can I do that? I can check by adding the following code under the validate code.
if (!($request['has_a_type'] || $request['has_b_type'] || $request['has_c_type'] || $request['has_d_type'] || $request['has_e_type'] || $request['has_f_type'])) {
return ...->withError();
}
But I wonder if there is a way to check this invalidate.
2
Answers
Searching the docs I saw the required_without_all rule which might be what you need.
You specify the other checkboes in the
bar,...
argument list, something likeI must admit that I’ve not used this rule myself, it just looks like it might be a good use for it.
You can create a custom validation rule to check if at least one checkbox is selected. First, generate a new rule using the following command.
This will create a new rule class in the
app/Rules
directory. In theAtLeastOneCheckbox
class, you can define the condition for the rule in thepasses
method.Then, you can use this rule to validate the checkboxes in your controller. This will ensure that at least one checkbox is selected when submitting the form.