Livewire File Upload | Image upload with preview in Livewire
views users.departments.blade.php
@extends('layouts.app')
@section('content')
<div>
@livewire('departments')
</div>
@endsection
views livewire.departments.blade.php
<div>
@if(Session::has('success'))
<span style="color: green;">{{Session::get('success')}} </span>
@endif
<form wire:submit.prevent="store">
<label>Photo</label>
<input type="file" wire:model="photo">
<br>
@error('photo') <span class="error">{{ $message }}</span> @enderror
@if ($photo)
Photo Preview:
<img src="{{ $photo->temporaryUrl() }}" width="200">
@endif
<br><br>
<label>Name</label>
<input type="text" wire:model="name"><br><br>
<label>Content</label>
<input type="text" wire:model="content"><br><br>
<button type="submit">Save</button>
</form>
</div>
App/Http/Livewire
Departments.php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Department;
use Intervention\Image\ImageManager;
class Departments extends Component
{
use WithFileUploads;
public $photo,$name,$content;
public function render()
{
return view('livewire.departments');
}
public function store()
{
$this->validate([
'photo' => 'image|max:1024', // 1MB Max
'name'=>'required',
'content'=>'required',
]);
$this->photo->store('UserPhoto');
$image=$this->photo->hashName();
$data=new Department;
$data->name=$this->name;
$data->content=$this->content;
$data->photo=$image;
$data->save();
session()->flash('success','Image Uploaded');
}
}
No comments