Search code examples
laravellaravel-validationlaravel-7

What's the best way to handle "Other" on a list of radio buttons or checkboxes


I have a list of checkboxes, e.g.

[] Tomatoes
[] Cucumbers
[] Pumpkins
[] Other

When you check Other a text field pops up. This gets stored in a single column vegetables as a JSON string.

FormRequest.php

    public function rules()
    {
        return [
            'vegetable' => 'required'
        ]
    }
form.html

<legend class="@error('diagnose') text-red-500 : text-gray-900 @enderror">
                                    Did you get any of the following diagnoses last week? *
                                </legend>
<form action="" method="post">
    <input name="vegetable[]" type="checkbox" value="Tomatoes">Tomatoes</input>
    <input name="vegetable[]" type="checkbox" value="Cucumbers">Cucumbers</input>
    <input name="vegetable[]" type="checkbox" value="Pumpkins">Pumpkins</input>
    <input name="vegetable[]" type="checkbox" value="Other">Other</input>
    <input name="???" type="text"></input>
</form>

The idea is for this last field to be named in such a way, so it's easy to:

  1. Show validation errors, ideally without having to check two fields (e.g. vegetable and vegetable_other)
  2. Add it's value to the JSON without too much ifs.

How can that be done in Laravel without creating a wall of code?


Solution

  • You can do that validate if vegetable is other

     public function rules()
        {
            return [
                 'vegetable' => 'required',
                 'vegetableName'=>'required_if:vegetable,Other'     
            ]
        }
    

    and in the form

    form.html
    
    <legend class="@error('diagnose') text-red-500 : text-gray-900 @enderror">
                                        Did you get any of the following diagnoses last week? *
                                    </legend>
    <form action="" method="post">
        <input name="vegetable" type="checkbox" value="Tomatoes">Tomatoes</input>
        <input name="vegetable" type="checkbox" value="Cucumbers">Cucumbers</input>
        <input name="vegetable" type="checkbox" value="Pumpkins">Pumpkins</input>
        <input name="vegetable" type="checkbox" value="Other">Other</input>
        <input name="vegetableName" type="text"></input>
    </form>