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(); } } }