authentikate/app/Livewire/Forms/UserProfile.php
Javier Feliz 392d14e0e1
All checks were successful
linter / quality (push) Successful in 6m47s
tests / ci (push) Successful in 11m57s
WIP
2025-07-27 23:15:54 -04:00

98 lines
2.7 KiB
PHP

<?php
namespace App\Livewire\Forms;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;
class UserProfile extends Component
{
use WithFileUploads;
// Profile info
public string $name = '';
public string $email = '';
public ?string $preferred_username = null;
public ?string $avatar = null;
#[Validate('image|max:10000')]
public $avatarUpload;
// Password
public string $current_password = '';
public string $password = '';
public string $password_confirmation = '';
public function mount(): void
{
$this->name = Auth::user()->name;
$this->email = Auth::user()->email;
$this->preferred_username = Auth::user()->preferred_username;
$this->avatar = Auth::user()->avatar;
}
/**
* Update the profile information for the currently authenticated user.
*/
public function updateProfileInformation(): void
{
$user = Auth::user();
$validated = $this->validate([
'name' => 'required|string|max:255',
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($user->id),
],
'preferred_username' => 'string|max:255'
]);
$user->fill($validated);
if (!empty($this->avatarUpload)) {
if (!empty($user->avatar)) {
Storage::disk('avatars')->delete($user->avatar);
}
$user->avatar = $this->avatarUpload->store(options: 'avatars');
}
$user->save();
$this->dispatch('profile-updated', name: $user->name);
}
public function updatePassword(): void
{
try {
$validated = $this->validate([
'current_password' => ['required', 'string', 'current_password'],
'password' => ['required', 'string', PasswordRule::defaults(), 'confirmed'],
]);
} catch (ValidationException $e) {
$this->reset('current_password', 'password', 'password_confirmation');
throw $e;
}
Auth::user()->update([
'password' => Hash::make($validated['password']),
]);
$this->reset('current_password', 'password', 'password_confirmation');
$this->dispatch('password-updated');
}
public function render()
{
return view('livewire.forms.user-profile');
}
}