Search code examples
phplaravellaravel-livewire

Laravel Livewire - Get all checkbox value


I've want to add filters on my table. My filters are the level of security of an account. There is my HTML

<input type="checkbox" value="O" wire:model="level" id="O">
<label for="O">O</label>
<input type="checkbox" value="a" wire:model="level" id="a">
<label for="a">A</label>
<input type="checkbox" value="b" wire:model="level" id="b">
<label for="b">B</label>
<input type="checkbox" value="c" wire:model="level" id="c">
<label for="c">C</label>

And there is my Livewire component:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\User;

class Compliance extends Component
{

    public $level = [];

    public function render()
    {
        return view('livewire.compliance', [
            'customers' => $this->row
        ]);
    }

    public function getRowsQueryProperty()
    {
        $query = User::query()
            ->when($this->level, fn($query, $levels) => $query->level($levels));

        return $query;
    }

    public function getRowsProperty()
    {
        return $this->rowsQuery->paginate(20);
    }
}

My problem is: $this->level is always only one value, not an array of value like

[
     0 => 'O',
     1 => 'a'
]

I would like to have all the checked checkbox everytime i check or uncheck a checkbox. Thanks for reading


Solution

  • You could add wire:click. For example, change your input fields like this:

    <input type="checkbox" wire:click="levelClicked" value="a" wire:model="level" id="a">
    

    And in the Compliance component, add a new method:

    public function levelClicked()
    {
        // now the property $this->level will contain all the selected values
    }