检索 ID 并选中相关框

Retrive ids and check related boxes

正在使用

Laravel 8.54

Livewire 2.6

Laratrust 角色和权限包

我想像这样编辑权限角色

RolesEdit.php(火线组件)

<?php
namespace App\Http\Livewire\Admin\Roles;

use App\Models\Role;
use Livewire\Component;
use App\Models\Permission;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;

class RolesEdit extends Component
{
  public $data = [];
  public $role;
  public $selectedIds = [];

  public function mount(Role $role)
  {
    $this->role = $role;
    $this->data = $role->toArray();
  }

  public function update()
  {
    $this->data['permissions'] = $this->selectedIds;
    $validated = Arr::except($this->validatedData(), ['permissions']);
    $this->role->update($validated);
    $this->role->permissions()->sync($this->data['permissions']);
  }

  public function validatedData()
  {
    return Validator::make($this->data, [
      'display_name' => 'required',
      'description' => 'required',
      "permissions"    => "required|array|min:1",
      "permissions.*"  => "required|distinct|min:1",
    ])->validate();
  }

  public function render()
  {
    $permissions = Permission::all();
    return view('livewire.admin.roles.roles-edit', compact('permissions'));
  }
}

角色-edit.blade.php


<div class="mt-1">
  <label class="form-label">{{ __('site.display_name') }}</label>
  <input wire:model="data.display_name" type="text" class="form-control" placeholder="Enter role name" />
</div>
<div class="mt-1">
  <label class="form-label">{{ __('site.role_description') }}</label>
  <textarea wire:model="data.description" type="text" class="form-control"
    placeholder="Enter Description"></textarea>
</div>

<div class="row w-100">
  @foreach ($permissions as $permission)
  <div class="col-md-3">
   <div class="form-check ms-5">
     <input wire:model.defer="selectedIds" class="form-check-input" id="{{ $permission->name }}"
            value="{{ $permission->id }}" type="checkbox"
            {{ $role->permissions->contains($permission->id) ? 'checked' : '' }} />
          <label class="form-check-label" for="{{ $permission->name }}">
        {{ $permission->display_name }}</label>
            </div>
          </div>
   @endforeach
</div>

当我打开 roles-edit 视图时,我想选中具有与角色相关的 $permission->id 的框,所以我使用

{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}

但它不起作用……所有复选框都未选中

改为使用代码:

{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}

试试这个

@if($role->permissions->contains($permission->id)) checked @endif

还尝试将 wire:key 指令添加到输入元素的父 div

<div class="form-check ms-5" wire:key="input-checkbox-{{ $permission->id }}">

我建议你创建一个数组来检索角色的权限 ID

public $permissionsIds = [];

public function mount(Role $role)
  {
    $this->role = $role;
    $this->data = $role->toArray();
    $this->permissionsIds = $this->role->permissions()->pluck('id');
  }

// in blade

@if(in_array($permission->id,$permissionsIds)) checked @endif