Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

speedydan's avatar

Validating an input array

I have a list of checkboxes on a form, like so

<li>
    <input type="checkbox" class="form-check-input" id="voluntary" name="classifications[]" value="Voluntary">
    <label class="form-check-label form__check-label" for="voluntary">Voluntary, Community and Social Enterprise (VCSE)</label>
</li>
<li>
    <input type="checkbox" class="form-check-input" id="workshop" name="classifications[]" value="Workshop">
    <label class="form-check-label form__check-label" for="workshop">Sheltered Workshop</label>
</li>
<li>
    <input type="checkbox" class="form-check-input" id="public-service" name="classifications[]" value="Public Service">
    <label class="form-check-label form__check-label" for="public-service">Public Service Mutual</label>
</li>
<li>
    <input type="checkbox" class="form-check-input" id="n/a" name="classifications[]" value="N/A">
    <label class="form-check-label form__check-label" for="n/a">N/A</label>
</li>

My question is firstly, how would I go about validating it so at least 1 option is required, I've seen a couple of methods but they don't seem to work for me... secondly - how could I show which is checked based off the old values?

Thanks in advance :-)

0 likes
1 reply
grenadecx's avatar

Validation that would go something like this:

$request->validate([
    "classifications"    => "required|array",
]);

I think this should work, since if all of them are empty, classifications doesn't get send at all. And since it's required to be an array, at least one needs to be set.

And as for the the old input, you could use (for example on the Voluntary, Community and Social)

@if(isset(old('classifications')) && in_array('Voluntary', old('classifications'))) checked @endif

Please or to participate in this conversation.