处理单选按钮或复选框列表上的 "Other" 的最佳方法是什么

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

我有一个复选框列表,例如

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

当您选中 Other 时,会弹出一个文本字段。这将作为 JSON 字符串存储在单个列 vegetables 中。

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>

最后一个字段的想法是以这种方式命名的,因此很容易:

  1. 显示验证错误,理想情况下无需检查两个字段(例如 vegetablevegetable_other
  2. 将它的值添加到 JSON 而无需太多 ifs。

如何在不创建代码墙的情况下在 Laravel 中完成?

你可以做到 验证蔬菜是否为其他

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

并在表格中

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>