0

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?

OurBG
  • 507
  • 1
  • 8
  • 22
  • You should provide some code, at the very least the HTML for those options and your method of sending the data to the server. It should be a simple answer, but I'd be making too many assumptions on your code to do so. In the meantime, check out this validation rule: https://laravel.com/docs/7.x/validation#rule-required-if – Tim Lewis Apr 03 '20 at 20:10
  • 1
    I eddited my code a bit for clarity – OurBG Apr 03 '20 at 20:18
  • Didn't get a chance to look at the update yesterday, but have a look at this question: https://stackoverflow.com/questions/43147584/laravel-validation-rules-if-value-exists-in-another-field-array Since it's an array, it looks like you have to use a combination of rules. – Tim Lewis Apr 04 '20 at 17:26

1 Answers1

0

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>
mohamed hassan
  • 479
  • 3
  • 6