Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
Theodory Avatar asked Sep 19 '25 12:09

Theodory


2 Answers

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

like image 150
Theodory Avatar answered Sep 22 '25 09:09

Theodory


First, I think that bind the element with the id property isn't a good idea. In your case, if the checks only is for the $user existence, then you don't need bind anything, just use the @if statement for that.

<input  type="checkbox" class="form-checkbox h-6 w-6" id="ids.{{$user->id}}" @if($selectedUsers->contains($user->id)) checked @endif> 
like image 30
Prospero Avatar answered Sep 22 '25 11:09

Prospero