añadir nuevas funcionalidades
This commit is contained in:
86
app/Livewire/ImageUploader.php
Normal file
86
app/Livewire/ImageUploader.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use Livewire\Component;
|
||||
use Livewire\WithFileUploads;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class ImageUploader extends Component
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
public $image;
|
||||
public $imagePath;
|
||||
public $fieldName; // Nombre del campo para el formulario
|
||||
public $label = 'Subir imagen'; // Etiqueta personalizable
|
||||
public $hover = false;
|
||||
|
||||
// Recibir parámetros si es necesario
|
||||
public function mount($fieldName = 'image_path', $label = 'Subir imagen')
|
||||
{
|
||||
$this->fieldName = $fieldName;
|
||||
$this->label = $label;
|
||||
}
|
||||
|
||||
public function updatedImage()
|
||||
{
|
||||
$this->validate([
|
||||
'image' => 'image|max:2048', // 2MB Max
|
||||
]);
|
||||
|
||||
// Subir automáticamente al seleccionar
|
||||
$this->uploadImage();
|
||||
}
|
||||
|
||||
public function uploadImage()
|
||||
{
|
||||
$this->validate([
|
||||
'image' => 'required|image|max:2048',
|
||||
]);
|
||||
|
||||
// Guardar la imagen
|
||||
$this->imagePath = $this->image->store('uploads', 'public');
|
||||
// Emitir evento con el nombre del campo y la ruta
|
||||
$this->dispatch('imageUploaded',
|
||||
field: $this->fieldName,
|
||||
path: $this->imagePath
|
||||
);
|
||||
}
|
||||
|
||||
public function save()
|
||||
{
|
||||
$this->validate([
|
||||
'image' => 'required|image|max:2048',
|
||||
]);
|
||||
|
||||
// Guardar la imagen
|
||||
$this->imagePath = $this->image->store('images', 'public');
|
||||
|
||||
// Emitir evento con el nombre del campo y la ruta
|
||||
$this->emit('imageUploaded', [
|
||||
'field' => $this->fieldName,
|
||||
'path' => $this->imagePath
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeImage()
|
||||
{
|
||||
$this->reset(['image', 'imagePath']);
|
||||
|
||||
// Cambiar emit por dispatch en Livewire v3+
|
||||
$this->dispatch('imageRemoved',
|
||||
field: $this->fieldName
|
||||
);
|
||||
}
|
||||
|
||||
public function toggleHover($status)
|
||||
{
|
||||
$this->hover = $status;
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.image-uploader');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user