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

dmhall0's avatar

Unchecking Checkbox returns false?

This is one confusing me!

I have a form with a foreach looping over positions creating input checkboxes for each position. The checked boxes go into an array.

<input wire:ignore.self class="form-check-input" type="checkbox" value="{{ $position->id }}" name="selectedPositions" wire:model.lazy="selectedPositions.{{ $position->id }}"  />

Everything works fine, except when I uncheck one, that is to say I accidentally checked the wrong one, it stays in the array but has a value of "false".

^ array:4 [▼
  1 => "1"
  2 => false
  3 => "3"
  7 => "7"
]

This throws an error on the save with an Integrity constraint violation on the "false".

$group->positions()->sync($this->selectedPositions);

How can I either, 1 - get around the error, or 2 - get the checked box removed from the array when I actually uncheck it?

Thanks for the help!

0 likes
9 replies
MohamedTammam's avatar

I believe the wire:model value should be

<input wire:ignore.self class="form-check-input" type="checkbox" value="{{ $position->id }}" name="selectedPositions" wire:model.lazy="selectedPositions"  />
1 like
dmhall0's avatar

@jlrdw Ideally the 2 => false would be completely removed from the array. Leaving it there is now causing an issue with my validation.

dmhall0's avatar

Okay, so that solution got me able to save the connected positions to the group, but I also need to validate that at least one position is checked. With the "false" return still in the array, it is not working. Here is my validation now

'selectedPositions' => ['required','integer','min:1'],

Any ideas?

webrobert's avatar

@dmhall0, livewire has a method that will run prior to validation...

public function prepareForValidation($attributes)
{
    $this->selectedPositions = array_filter($this->selectedPositions);

    return $attributes;
}
1 like
dmhall0's avatar

@webrobert Perfect! Clearly I have A TON to learn. Thank you for all your help!

1 like

Please or to participate in this conversation.