livewire multiple file/image upload with preview
App/Http/Livewire/Students.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
class Students extends Component
{
use WithFileUploads;
public $photos=[];
public function removeImg($index)
{
array_splice($this->photos, $index);
}
public function save()
{
$this->validate([
'photos.*' => 'image|max:1024', // 1MB Max
]);
foreach ($this->photos as $photo) {
$photo->store('images');
}
}
public function render()
{
return view('livewire.students');
}
}
Resource
Views
backend.students.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Departments</title>
@livewireStyles
</head>
<body>
<div class="container">
@livewire('students')
</div>
@livewireScripts
</body>
</html>
Views
livewire/students.blade.php
<div>
<form>
<input type="file" wire:model="photos" multiple>
@error('photos.*') <span class="error">{{ $message }}</span> @enderror
@if ($photos)
@foreach($photos as $photo)
<img src="{{ $photo->temporaryUrl() }}" width="100">
<button wire:click.prevent="removeImg({{$loop->index}})">
Remove
</button>
@endforeach
@endif
<button wire:click.prevent="save()">Save</button>
</form>
</div>
Route
web.php
Route::view('students','backend.students');
No comments