feat(roles): role CRUD screen (list + form name/description + view/edit/delete + bulk)

Per request:
- Migration: add nullable 'description' to the roles table.
- RoleManager Livewire component + view at /admin/roles:
  * Roles list table with per-row checkboxes for bulk selection (+ select-all)
    and a 'Delete selected' bulk action (protected roles skipped).
  * 'New role' opens a modal form with just Name + Description (and permission
    checkboxes to assign).
  * Per-row View / Edit / Delete buttons (View modal shows description,
    counts and assigned permissions).
- Admin role stays protected (no rename/delete/lose 'manage all').
- /admin/users links to the new Roles screen; the phase-1 permission matrix
  stays available via a 'Matrix view' link.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-17 16:57:59 +02:00
parent 828e70fbe2
commit 938e704a67
5 changed files with 389 additions and 2 deletions
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;
#[Layout('layouts.app')]
class RoleManager extends Component
{
// Create / edit modal
public bool $showForm = false;
public ?int $editingRole = null;
public string $name = '';
public string $description = '';
public array $rolePermissions = []; // selected permission names
// View modal
public ?int $viewingRole = null;
// Bulk selection
public array $selected = [];
public bool $selectAll = false;
private const PROTECTED_ROLES = ['Admin'];
private const CORE_PERMISSION = 'manage all';
public function mount(): void
{
abort_unless(Auth::user()?->can(self::CORE_PERMISSION), 403);
}
private function flushCache(): void
{
app(PermissionRegistrar::class)->forgetCachedPermissions();
}
public function updatedSelectAll($value): void
{
$this->selected = $value
? Role::pluck('id')->map(fn ($id) => (string) $id)->toArray()
: [];
}
// ── Create / Edit ────────────────────────────────────────────────────────
public function openCreate(): void
{
$this->resetForm();
$this->showForm = true;
}
public function openEdit(int $id): void
{
$role = Role::with('permissions')->findOrFail($id);
$this->editingRole = $role->id;
$this->name = $role->name;
$this->description = $role->description ?? '';
$this->rolePermissions = $role->permissions->pluck('name')->toArray();
$this->resetErrorBag();
$this->viewingRole = null; // close the view modal if open
$this->showForm = true;
}
public function save(): void
{
$this->validate([
'name' => 'required|string|max:50|unique:roles,name' . ($this->editingRole ? ',' . $this->editingRole : ''),
'description' => 'nullable|string|max:255',
], [], ['name' => 'nombre', 'description' => 'descripción']);
if ($this->editingRole) {
$role = Role::findOrFail($this->editingRole);
$isProtected = in_array($role->name, self::PROTECTED_ROLES, true);
// Protected roles can't be renamed
if (! $isProtected) {
$role->name = $this->name;
}
$role->description = $this->description ?: null;
$role->save();
$perms = $this->rolePermissions;
// Admin always keeps the core permission
if ($role->name === 'Admin' && ! in_array(self::CORE_PERMISSION, $perms, true)) {
$perms[] = self::CORE_PERMISSION;
}
$role->syncPermissions($perms);
} else {
$role = Role::create([
'name' => $this->name,
'description' => $this->description ?: null,
]);
if (! empty($this->rolePermissions)) {
$role->syncPermissions($this->rolePermissions);
}
}
$this->flushCache();
$this->closeForm();
$this->dispatch('notify', 'Rol guardado correctamente');
}
public function closeForm(): void
{
$this->showForm = false;
$this->resetForm();
}
private function resetForm(): void
{
$this->reset(['editingRole', 'name', 'description', 'rolePermissions']);
$this->resetErrorBag();
}
// ── View ─────────────────────────────────────────────────────────────────
public function openView(int $id): void
{
$this->viewingRole = $id;
}
public function closeView(): void
{
$this->viewingRole = null;
}
// ── Delete (single / bulk) ─────────────────────────────────────────────────
public function delete(int $id): void
{
$role = Role::findOrFail($id);
if (in_array($role->name, self::PROTECTED_ROLES, true)) {
$this->dispatch('notify', "El rol '{$role->name}' está protegido y no se puede borrar.");
return;
}
$role->delete();
$this->selected = array_values(array_diff($this->selected, [(string) $id, $id]));
$this->flushCache();
$this->dispatch('notify', 'Rol eliminado');
}
public function bulkDelete(): void
{
$roles = Role::whereIn('id', $this->selected)->get();
$deleted = 0;
$skipped = 0;
foreach ($roles as $role) {
if (in_array($role->name, self::PROTECTED_ROLES, true)) { $skipped++; continue; }
$role->delete();
$deleted++;
}
$this->selected = [];
$this->flushCache();
$msg = "{$deleted} rol(es) eliminados";
if ($skipped) $msg .= " ({$skipped} protegido(s) omitido(s))";
$this->dispatch('notify', $msg);
}
public function render()
{
return view('livewire.role-manager', [
'roles' => Role::with('permissions')->withCount('users')->orderBy('name')->get(),
'permissions' => Permission::orderBy('name')->get(),
'viewing' => $this->viewingRole
? Role::with('permissions')->withCount('users')->find($this->viewingRole)
: null,
]);
}
}
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$table = config('permission.table_names.roles', 'roles');
Schema::table($table, function (Blueprint $table) {
if (! Schema::hasColumn($table->getTable(), 'description')) {
$table->string('description')->nullable()->after('name');
}
});
}
public function down(): void
{
$table = config('permission.table_names.roles', 'roles');
Schema::table($table, function (Blueprint $table) {
if (Schema::hasColumn($table->getTable(), 'description')) {
$table->dropColumn('description');
}
});
}
};
+2 -2
View File
@@ -6,8 +6,8 @@
</h2>
<div class="flex items-center gap-2">
<a href="{{ route('admin.permissions') }}" class="btn btn-outline btn-sm gap-1" wire:navigate>
<x-heroicon-o-shield-check class="w-4 h-4" /> {{ __('Permissions') }}
<a href="{{ route('admin.roles') }}" class="btn btn-outline btn-sm gap-1" wire:navigate>
<x-heroicon-o-shield-check class="w-4 h-4" /> {{ __('Roles & permissions') }}
</a>
<a href="{{ route('admin.users.create') }}" class="btn btn-primary btn-sm gap-1" wire:navigate>
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('New user') }}
@@ -0,0 +1,182 @@
<div class="py-8 max-w-6xl mx-auto sm:px-6 lg:px-8">
{{-- Cabecera --}}
<div class="flex items-center justify-between mb-6">
<div>
<h2 class="text-2xl font-bold text-gray-800">{{ __('Roles & permissions') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ __('Manage role groups and the permissions assigned to each.') }}</p>
</div>
<div class="flex items-center gap-2">
<a href="{{ route('admin.permissions') }}" class="btn btn-outline btn-sm gap-1" wire:navigate>
<x-heroicon-o-table-cells class="w-4 h-4" /> {{ __('Matrix view') }}
</a>
<button wire:click="openCreate" class="btn btn-primary btn-sm gap-1">
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('New role') }}
</button>
</div>
</div>
{{-- Barra de acciones en grupo --}}
@if(count($selected) > 0)
<div class="flex items-center justify-between bg-base-200 rounded-lg px-4 py-2 mb-3">
<span class="text-sm">{{ count($selected) }} {{ __('selected') }}</span>
<button wire:click="bulkDelete"
wire:confirm="{{ __('Delete the selected roles? Protected roles will be skipped.') }}"
class="btn btn-error btn-sm gap-1">
<x-heroicon-o-trash class="w-4 h-4" /> {{ __('Delete selected') }}
</button>
</div>
@endif
{{-- Tabla de roles --}}
<div class="overflow-x-auto border border-base-300 rounded-lg bg-white">
<table class="table table-zebra">
<thead>
<tr>
<th class="w-10">
<input type="checkbox" class="checkbox checkbox-sm" wire:model.live="selectAll" />
</th>
<th>{{ __('Name') }}</th>
<th>{{ __('Description') }}</th>
<th class="text-center">{{ __('Permissions') }}</th>
<th class="text-center">{{ __('Users') }}</th>
<th class="w-32 text-right">{{ __('Actions') }}</th>
</tr>
</thead>
<tbody>
@forelse($roles as $role)
<tr wire:key="role-{{ $role->id }}" class="hover">
<td>
<input type="checkbox" class="checkbox checkbox-sm"
value="{{ $role->id }}" wire:model.live="selected" />
</td>
<td class="font-semibold">
{{ $role->name }}
@if(in_array($role->name, ['Admin'], true))
<span class="badge badge-ghost badge-xs ml-1">{{ __('protected') }}</span>
@endif
</td>
<td class="text-sm text-gray-500 max-w-xs truncate">{{ $role->description ?: '—' }}</td>
<td class="text-center">
<span class="badge badge-outline badge-sm">{{ $role->permissions->count() }}</span>
</td>
<td class="text-center">
<span class="badge badge-ghost badge-sm">{{ $role->users_count }}</span>
</td>
<td class="text-right">
<div class="flex items-center justify-end gap-1">
<button wire:click="openView({{ $role->id }})" class="btn btn-ghost btn-xs" title="{{ __('View') }}">
<x-heroicon-o-eye class="w-4 h-4" />
</button>
<button wire:click="openEdit({{ $role->id }})" class="btn btn-ghost btn-xs text-info" title="{{ __('Edit') }}">
<x-heroicon-o-pencil class="w-4 h-4" />
</button>
@unless(in_array($role->name, ['Admin'], true))
<button wire:click="delete({{ $role->id }})"
wire:confirm="{{ __('Delete role') }} '{{ $role->name }}'?"
class="btn btn-ghost btn-xs text-error" title="{{ __('Delete') }}">
<x-heroicon-o-trash class="w-4 h-4" />
</button>
@endunless
</div>
</td>
</tr>
@empty
<tr><td colspan="6" class="text-center text-gray-400 py-8">{{ __('No roles') }}</td></tr>
@endforelse
</tbody>
</table>
</div>
{{-- ════════════════ MODAL CREAR / EDITAR ════════════════ --}}
@if($showForm)
<div class="modal modal-open z-[1500]">
<div class="modal-box max-w-xl">
<div class="flex items-center justify-between mb-4">
<h3 class="font-bold text-lg">{{ $editingRole ? __('Edit role') : __('New role') }}</h3>
<button wire:click="closeForm" class="btn btn-sm btn-circle btn-ghost"><x-heroicon-o-x-mark class="w-5 h-5" /></button>
</div>
<form wire:submit.prevent="save" class="space-y-4">
{{-- Nombre --}}
<div class="form-control">
<label class="label"><span class="label-text font-medium">{{ __('Name') }} <span class="text-error">*</span></span></label>
<input type="text" wire:model="name"
class="input input-bordered w-full @error('name') input-error @enderror"
placeholder="{{ __('e.g. Site Supervisor') }}"
@if($editingRole && in_array($name, ['Admin'], true)) readonly @endif />
@error('name') <span class="text-error text-xs mt-1">{{ $message }}</span> @enderror
</div>
{{-- Descripción --}}
<div class="form-control">
<label class="label"><span class="label-text font-medium">{{ __('Description') }}</span></label>
<textarea wire:model="description" rows="2"
class="textarea textarea-bordered w-full @error('description') textarea-error @enderror"
placeholder="{{ __('What is this role for?') }}"></textarea>
@error('description') <span class="text-error text-xs mt-1">{{ $message }}</span> @enderror
</div>
{{-- Permisos --}}
<div class="form-control">
<label class="label"><span class="label-text font-medium">{{ __('Permissions') }}</span></label>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-1 border border-base-300 rounded-lg p-3 max-h-60 overflow-y-auto">
@foreach($permissions as $perm)
<label class="flex items-center gap-2 text-sm cursor-pointer py-0.5">
<input type="checkbox" class="checkbox checkbox-sm checkbox-primary"
value="{{ $perm->name }}" wire:model="rolePermissions" />
{{ $perm->name }}
</label>
@endforeach
</div>
</div>
<div class="modal-action">
<button type="button" wire:click="closeForm" class="btn btn-ghost">{{ __('Cancel') }}</button>
<button type="submit" class="btn btn-primary gap-1" wire:loading.attr="disabled" wire:target="save">
<span wire:loading wire:target="save" class="loading loading-spinner loading-sm"></span>
{{ $editingRole ? __('Update') : __('Create') }}
</button>
</div>
</form>
</div>
<div class="modal-backdrop bg-black/40" wire:click="closeForm"></div>
</div>
@endif
{{-- ════════════════ MODAL VER ════════════════ --}}
@if($viewing)
<div class="modal modal-open z-[1500]">
<div class="modal-box max-w-lg">
<div class="flex items-center justify-between mb-3">
<h3 class="font-bold text-lg flex items-center gap-2">
<x-heroicon-o-shield-check class="w-5 h-5 text-primary" /> {{ $viewing->name }}
</h3>
<button wire:click="closeView" class="btn btn-sm btn-circle btn-ghost"><x-heroicon-o-x-mark class="w-5 h-5" /></button>
</div>
<p class="text-sm text-gray-600 mb-1">{{ $viewing->description ?: __('No description') }}</p>
<p class="text-xs text-gray-400 mb-4">{{ $viewing->users_count }} {{ __('users') }} · {{ $viewing->permissions->count() }} {{ __('permissions') }}</p>
<div class="divider text-xs">{{ __('Permissions') }}</div>
@if($viewing->permissions->isEmpty())
<p class="text-sm text-gray-400">{{ __('No permissions') }}</p>
@else
<div class="flex flex-wrap gap-1">
@foreach($viewing->permissions as $perm)
<span class="badge badge-primary badge-sm">{{ $perm->name }}</span>
@endforeach
</div>
@endif
<div class="modal-action">
<button wire:click="openEdit({{ $viewing->id }})" class="btn btn-sm btn-info gap-1">
<x-heroicon-o-pencil class="w-4 h-4" /> {{ __('Edit') }}
</button>
<button wire:click="closeView" class="btn btn-sm">{{ __('Close') }}</button>
</div>
</div>
<div class="modal-backdrop bg-black/40" wire:click="closeView"></div>
</div>
@endif
</div>
+1
View File
@@ -136,6 +136,7 @@ Route::get('/reports/dashboard', ReportsDashboard::class)->name('reports.dashboa
Route::get('/users/create', \App\Livewire\UserForm::class)->name('users.create');
Route::get('/users/{user}', \App\Livewire\UserView::class)->name('users.show');
Route::get('/users/{user}/edit', \App\Livewire\UserForm::class)->name('users.edit');
Route::get('/roles', \App\Livewire\RoleManager::class)->name('roles');
Route::get('/permissions', \App\Livewire\RolePermissionManager::class)->name('permissions');
});