Hello Dear all,
I am trying to implement role permission using Livewire, so I can save permission on a specific Role. But when I am trying to edit a Role but the given permission being unchecked in checkbox. I inspect the html element and I found that the checked attribute is printed successfully. any one help me please?? Here is my component Class and Blade code I share with you.
@foreach ($permissions as $id => $title)
<div class="col-md-4">
<div class="switch-label">{{$title}}</div>
<div class="custom-control custom-switch custom-control-inline">
<input type="checkbox" class="custom-control-input" name="permission_input" id="permission_input{{$id}}" value="{{$id}}" @if($role_obj->permissions->contains($id))checked @endif wire:model="permission_input.{{$id}}">
<label class="custom-control-label" for="permission_input{{$id}}"></label>
</div>
</div>
</div>
@endforeach
<?php
namespace App\Http\Livewire;
use App\Models\Permission;
use App\Models\Role;
use Livewire\Component;
class RoleComponent extends Component
{
public $role_id, $role_obj, $confirming, $title, $permission_input, $permissions = [];
public $show = true, $create = false, $edit = false;
protected $messages = [
'title.required' => 'Enter a Role name',
'title.unique' => 'Given Role exist',
'permission_input.required' => 'Select some permission for this role',
];
private function resetInput()
{
$this->title = null;
$this->permission_input = null;
}
public function show()
{
$this->edit = false;
$this->show = true;
$this->create = false;
}
public function create()
{
$this->permissions = Permission::pluck('title', 'id');
$this->edit = false;
$this->show = false;
$this->create = true;
}
public function store()
{
$this->validate([
'title' => 'required|unique:roles,title',
'permission_input' => 'required'
]);
$inserted_id = Role::create([
'title' => $this->title
])->permissions()->sync($this->permission_input, []);
$this->resetInput();
$this->edit = false;
$this->show = true;
$this->create = false;
}
public function edit($id)
{
$role = Role::with('permissions')->findOrFail($id);
$this->permissions = Permission::pluck('title', 'id');
$this->role_id = $id;
$this->title = $role->title;
$this->role_obj = $role;
$this->edit = true;
$this->show = false;
$this->create = false;
}
public function update()
{
$this->validate([
'title' => 'required',
'permission_input' => 'required'
]);
$inserted_id = Role::whereId($this->role_id)->update([
'title' => $this->title
])->permissions()->sync($this->permission_input, []);
$this->resetInput();
$this->edit = false;
$this->show = true;
$this->create = false;
}
public function confirm_delete($id)
{
$this->confirming = $id;
}
public function cancel_delete($id)
{
$this->confirming = null;
}
public function destroy($id)
{
if ($id) {
Role::where('id', $id)->delete();
}
}
public function render()
{
return view('livewire.role.component', [
'roles' => Role::with('permissions')->paginate(50)
]);
}
}