Checkboxes with "select all" option

I have a Livewire module that contains a table with contacts. Each row has a checkbox, giving the user the ability to select multiple contacts to edit. When the user selects a row, an ‘edit selected’ button appears, giving the user the ability to edit multiple rows.

I have a public property of $selectedIds, which is initially set as an empty array. As rows are checked, the values of these checkboxes (the database id for each contact) is pushed into the array so that the selected IDs can be edited. This is all working as it should.

My boss asked me today to add functionality that includes the ability to ‘check all’, which would select all rows for editing.

Steps to Reproduce:

In order to accomplish this, I added a property named $selected that is set to false by default. I have a simple


attached to the “select all” checkbox, which toggles the $selected property to true when the checkbox is checked.

On each row of the table, the select checkboxes have:

@if($selected !== false) checked @endif

If I inspect element, I can see that this is working as it should, and “checked” is being added to the inputs, but the HTML output doesn’t reflect the checkboxes as checked. In addition to this, even though these checkboxes are checked, the values are not being added to the $selectedIds array as they would normally be if the user clicked the checkbox on each row manually.

Are you using the latest version of Livewire: Yes

Do you have any screenshots or code examples:

public $selected = false;
public $selectedIds = [];

<input wire:click="$toggle('selected')" type="checkbox" />

<input wire:model="selectedIds" type="checkbox" name="select" value="{{ $contact->id }}" @if($selected !== false) checked @endif >

Few things to consider / try:

  • Make correct link to a wire:model, you need to add a array key to the model like:

<input wire:model="selectedIds.{{ $contact->id }}"`

  • Add ID attribute to checkboxes.
  • You may need to pre-initialize selectedIds with unchecked values as null.

You may also take a look at ready to use table components.

You should check out Caleb’s latest video series on Data Tables. He tackles this exact issue in this episode:

He even shows you how to handle select all across multiple pages of paginated rows.

Wow. I had watched all of the screencasts a while back but totally missed these. Literally the exact issue, right down to the ‘boss wants it’ part, lol. Thanks!

1 Like