2026-06-17 17:05:01 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Livewire;
|
|
|
|
|
|
|
|
|
|
use Livewire\Component;
|
|
|
|
|
use Livewire\Attributes\Layout;
|
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
|
use Spatie\Permission\Models\Role;
|
|
|
|
|
use Spatie\Permission\PermissionRegistrar;
|
|
|
|
|
|
|
|
|
|
#[Layout('layouts.app')]
|
|
|
|
|
class RoleForm extends Component
|
|
|
|
|
{
|
|
|
|
|
public ?Role $role = null;
|
|
|
|
|
|
|
|
|
|
public string $name = '';
|
|
|
|
|
public string $description = '';
|
|
|
|
|
|
|
|
|
|
private const PROTECTED_ROLES = ['Admin'];
|
|
|
|
|
private const CORE_PERMISSION = 'manage all';
|
|
|
|
|
|
|
|
|
|
public function mount(?Role $role = null): void
|
|
|
|
|
{
|
|
|
|
|
abort_unless(Auth::user()?->can(self::CORE_PERMISSION), 403);
|
|
|
|
|
|
|
|
|
|
if ($role && $role->exists) {
|
2026-06-17 17:21:16 +02:00
|
|
|
$this->role = $role;
|
|
|
|
|
$this->name = $role->name;
|
|
|
|
|
$this->description = $role->description ?? '';
|
2026-06-17 17:05:01 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function save()
|
|
|
|
|
{
|
|
|
|
|
$this->validate([
|
|
|
|
|
'name' => 'required|string|max:50|unique:roles,name' . ($this->role ? ',' . $this->role->id : ''),
|
|
|
|
|
'description' => 'nullable|string|max:255',
|
|
|
|
|
], [], ['name' => 'nombre', 'description' => 'descripción']);
|
|
|
|
|
|
|
|
|
|
if ($this->role) {
|
2026-06-17 17:21:16 +02:00
|
|
|
// Protected roles can't be renamed
|
|
|
|
|
if (! in_array($this->role->name, self::PROTECTED_ROLES, true)) {
|
2026-06-17 17:05:01 +02:00
|
|
|
$this->role->name = $this->name;
|
|
|
|
|
}
|
|
|
|
|
$this->role->description = $this->description ?: null;
|
|
|
|
|
$this->role->save();
|
|
|
|
|
} else {
|
2026-06-17 17:21:16 +02:00
|
|
|
Role::create([
|
2026-06-17 17:05:01 +02:00
|
|
|
'name' => $this->name,
|
|
|
|
|
'description' => $this->description ?: null,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
app(PermissionRegistrar::class)->forgetCachedPermissions();
|
|
|
|
|
session()->flash('message', 'Rol guardado correctamente.');
|
|
|
|
|
|
|
|
|
|
return $this->redirect(route('admin.roles'), navigate: true);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function render()
|
|
|
|
|
{
|
|
|
|
|
return view('livewire.roles.role-form', [
|
|
|
|
|
'isProtected' => $this->role && in_array($this->role->name, self::PROTECTED_ROLES, true),
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
}
|