Search code examples
phplaravellaravel-validation

Laravel validation not allow to be false all


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.


Solution

  • I have two possible solutions for your problem:

    One is using required_without_all

    $request = $request->validate([
    ...
    'has_a_type' => 'required_without_all','has_b_type','has_c_type' ...
    'has_b_type' => ...
    ...
    ]);
    

    Another better solution is passing data in array

    <input type="checkbox" name="has_type[]" value="a">
    <input type="checkbox" name="has_type[]" value="b">
    ...
    
    $request = $request->validate([
    ...
    'has_type' => 'required',
    ])
    ;
    

    NOTE: In both solutions you will need to remove those hidden fields: <input type="hidden" name="has_a_type" value="0">