Files
Nexora/app/Livewire/ImageUploader.php
Javi f97a7a8498
Some checks failed
linter / quality (push) Has been cancelled
tests / ci (push) Has been cancelled
añadir nuevas funcionalidades
2025-04-30 20:56:28 +02:00

80 lines
1.9 KiB
PHP

<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;
class ImageUploader extends Component
{
use WithFileUploads;
public $photo;
public $currentImage;
public $fieldName;
public $placeholder;
public $storagePath = 'tmp/uploads';
protected $rules = [
'photo' => 'nullable|image|max:2048', // 2MB Max
];
public function mount($fieldName = 'photo', $currentImage = null, $placeholder = null)
{
$this->fieldName = $fieldName;
$this->currentImage = $currentImage;
$this->placeholder = $placeholder ?? asset('images/default-avatar.png');
}
public function updatedPhoto()
{
$this->validate([
'photo' => 'image|max:2048', // 2MB Max
]);
}
public function removePhoto()
{
$this->photo = null;
$this->currentImage = null;
}
public function save()
{
$this->validate();
if ($this->photo) {
$path = $this->photo->store($this->storagePath);
if ($this->model) {
// Eliminar imagen anterior si existe
if ($this->model->{$this->fieldName}) {
Storage::delete($this->model->{$this->fieldName});
}
$this->model->{$this->fieldName} = $path;
$this->model->save();
}
$this->currentUrl = Storage::url($path);
$this->showSavedMessage = true;
$this->photo = null; // Limpiar el input de subida
}
}
protected function getCurrentImageUrl()
{
if ($this->model && $this->model->{$this->fieldName}) {
return Storage::url($this->model->{$this->fieldName});
}
return $this->placeholder;
}
public function render()
{
return view('livewire.image-uploader');
}
}