Files
zenithar/app/Livewire/Usuarios/Edit.php

131 lines
3.3 KiB
PHP

<?php
namespace App\Livewire\Usuarios;
use App\Enums\RoleName;
use App\Models\Role;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
use TallStackUi\Traits\Interactions;
class Edit extends Component
{
use Interactions;
#[Locked]
public ?User $user = null;
public $name = null;
public $email = null;
public $password = null;
public $password_confirmation = null;
public $roles = [];
public $change_password = false;
public function mount(): void
{
if ($this->user) {
$this->name = $this->user->name;
$this->email = $this->user->email;
$this->roles = $this->user->roles()->pluck('id')->toArray();
}
}
public function render(): View
{
return view('livewire.usuarios.edit');
}
public function rules(): array
{
return [
'name' => 'required|string',
'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($this->user?->id)],
'password' => $this->change_password ? 'required|string|min:8|confirmed' : 'nullable|string|min:8|confirmed',
'password_confirmation' => $this->change_password ? 'required' : 'nullable',
'roles' => 'nullable',
];
}
public function save(): void
{
$this->validate();
if ($this->user) {
$this->update();
} else {
$this->store();
}
$this->redirectRoute('usuarios.index', navigate: true);
}
public function update(): void
{
$this->authorize('update', $this->user);
$this->user->name = $this->name;
$this->user->email = $this->email;
if ($this->change_password) {
$this->user->password = Hash::make($this->password);
}
$this->user->save();
$isSuperAdmin = $this->user->isAn(RoleName::SuperAdmin);
if($isSuperAdmin) {
$this->roles[] = Role::where('name', RoleName::SuperAdmin)->first()->id;
}
$this->user->roles()->sync($this->roles);
$this->toast()->success("Éxito", "Usuario modificado correctamente")->flash()->send();
}
public function store(): void
{
$this->authorize('create', User::class);
$superadmin = Role::whereName(RoleName::SuperAdmin)->first();
if(collect($this->roles)->contains($superadmin->id)) {
Gate::authorize('create-super-admin', User::class);
}
$user = User::create([
'name' => $this->name,
'email' => $this->email,
'password' => Hash::make($this->password),
]);
$user->roles()->sync($this->roles);
$this->toast()->success("Éxito", "Usuario registrado correctamente")->flash()->send();
}
#[Computed]
public function availableRoles(): Collection
{
if(Gate::allows('create-super-admin', User::class)) {
return Role::all();
} else {
return Role::whereNot('name', RoleName::SuperAdmin)->get();
}
}
}