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->roles()->where('name', RoleName::SuperAdmin)->exists(); $this->user->roles()->sync($this->roles); if ($isSuperAdmin) { $this->user->roles()->attach(Role::where('name', RoleName::SuperAdmin)->first()->id); } Session::flash('toast', ['type' => 'success', 'message' => 'Usuario modificado correctamente']); } public function store(): void { $this->authorize('create', User::class); $user = User::create([ 'name' => $this->name, 'email' => $this->email, 'password' => Hash::make($this->password), ]); $user->roles()->sync($this->roles); Session::flash('toast', ['type' => 'success', 'message' => 'Usuario registrado correctamente']); } #[Computed] public function availableRoles(): Collection { return Role::whereNot('name', RoleName::SuperAdmin)->get(); } }