allPermissions = Permission::orderBy('name') ->get(['id', 'name']) ->toArray(); } public function updatedPerPage(int $value): void { $this->resetPage(); } #[On('roleSaved')] public function showIndex(): void { $this->mode = 'index'; $this->resetPage(); $this->name = ''; $this->editingId = null; $this->assignedPermissions = []; } public function updatedSearch(string $value): void { $this->resetPage(); } public function showForm(?int $id = null): void { $this->mode = 'form'; $this->editingId = $id; if ($id) { $role = Role::findOrFail($id); $this->name = $role->name; $this->assignedPermissions = $role ->permissions ->pluck('id') ->toArray(); } else { $this->name = ''; $this->assignedPermissions = []; } } /** * Delete a role by its ID. */ public function delete(int $id): void { Role::findOrFail($id)->delete(); session()->flash('message', 'Role deleted.'); $this->resetPage(); } public function save(): void { $uniqueRule = 'unique:roles,name' . ($this->editingId ? ',' . $this->editingId : ''); $this->validate([ 'name' => "required|string|{$uniqueRule}", 'assignedPermissions.*' => 'integer|exists:permissions,id', ]); $role = Role::updateOrCreate( ['id' => $this->editingId], ['name' => $this->name] ); // Sync permissions theo ID $role->permissions()->sync($this->assignedPermissions); session()->flash('message', 'Role saved.'); $this->dispatch('roleSaved'); } protected function computeTitle(): string { if ($this->mode === 'index') { return 'Roles'; } if ($this->mode === 'form' && $this->editingId) { return "Edit Role: {$this->name}"; } return 'Create Role'; } public function getTitleProperty(): string { return $this->computeTitle(); } public function render() { $roles = Role::with('permissions') // ← Eager-load permissions ->when($this->search, fn($q) => $q->where('name', 'like', "%{$this->search}%")) ->orderByDesc('id') ->paginate($this->perPage); return view('components.role.manager', [ 'roles' => $roles, 'title' => $this->title, ]); } }