Search code examples
laravellaravel-livewire

How to work with checkboxes in Laravel Livewire


I'm working with checkboxes in Laravel and Livewire, I have a problem on editing record I can get to checked ids users were selected during record creation.

Here is my flow

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Job Title</th>
            <th>Status</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @if (isset($members)) @foreach ($members as $key=>$user)
        <tr>
            <td>{{++$key}}.</td>
            <td class="text-capitalize">{{$user->full_name ?? ''}}</td>
            <td>{{$user->title->name ?? ''}}</td>
            <td>{!!$user->current_status ?? ''!!}</td>
            <td><input type="checkbox" class="form-checkbox h-6 w-6" wire:model.debounce.50000ms="ids.{{$user->id}}" value="{{$user->id}}" id="ids.{{$user->id}}" @if($selectedUsers- />contains($user->id)) checked @endif></td>
        </tr>

        @endforeach @endif
    </tbody>
</table>
@if (isset($members)) {{ $members->links() }} @endif

How can I check these checkboxes based on ids stored in the database?


Solution

  • I was able to make it work by initiating public $selectedUsers = [];

    Then On my livewire component

    <input  type="checkbox" class="form-control" wire:model.defer="selectedUsers" value="{{$user->id}}"  @if($selectedUsers->contains($user->id)) checked @endif>
    
    

    On editing make sure you take ids that was stored during record creation from the database and assign them to $this->selectedUsers.

    $this->selectedUsers = $this->production->users()->whereTitleId($this->request->title_id)->with('title:id,name')->pluck('id);
    
    

    Everything should work fine, cheers