如何在 Laravel Livewire 中使用复选框

How to work with checkboxes in Laravel Livewire

我正在使用 Laravel Livewire 中的复选框,我在编辑记录时遇到问题 我可以查看在创建记录时选择的用户 ID。

这是我的流程

     <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

如何根据存储在数据库中的 ID 检查这些复选框?

首先,我认为用 id 属性 绑定元素不是一个好主意。在你的情况下,如果检查只是为了 $user 存在,那么你不需要绑定任何东西,只需使用 @if 语句即可。

<input  type="checkbox" class="form-checkbox h-6 w-6" id="ids.{{$user->id}}" @if($selectedUsers->contains($user->id)) checked @endif> 

我能够通过启动 public $selectedUsers = [];

使其工作

然后在我的 livewire 组件上

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

编辑时确保从数据库中获取记录创建期间存储的 ID,并将它们分配给 $this->selectedUsers

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

一切正常,干杯

在我的例子中,我在 mount() 函数中检索用户,然后关联到 $selectedUsers 数组,将 id 设置为键,将值设置为字符串。

$userList = Users::select('id')->get();
foreach ($userList as $item){
    $this->selectedUsers[$item->id] = $item->id . '';
}

在我的组件中,我这样说:

<input type="checkbox" value="{{ $user->id }}" wire:model.defer="selectedUsers.{{ $user->id }}" />{{ $user->name }}