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:
vegetable
and vegetable_other
)if
s.How can that be done in Laravel without creating a wall of code?
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>