Laravel Livewire image upload with intervention image
at first install intervention/image
composer require intervention/image
After you have installed Intervention Image, open your Laravel config file config/app.php
and add the following lines.
In the $providers
array add the service providers for this package.
Intervention\Image\ImageServiceProvider::class
Add the facade of this package to the $aliases
array.
'Image' => Intervention\Image\Facades\Image::class
livewire/departments.php
<?php
namespace App\Http\Livewire;
use Livewire\WithFileUploads;
use Livewire\Component;
use App\Models\Department;
use Image;
class Departments extends Component
{
use WithFileUploads;
public $photo, $name, $content;
public function render()
{
return view('livewire.departments');
}
public function save()
{
$this->validate([
'photo' => 'image|max:10024',
'name'=>'max:20',
'content'=>'min:3|max:12',
]);
//$this->photo->store('photos');
// $imagehash=$this->photo->hashName();
//$manager = new ImageManager();
// to finally create image instances
//$image = $manager->make($this->photo)->resize(300, 200);
//$image->save('photos/'.$imagehash);
$image=$this->photo;
$file_name=time().'.'.$image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
$image_resize->save('photos/'.$file_name);
$data=new Department;
$data->photo= $file_name;
$data->name=$this->name;
$data->content=$this->content;
$data->save();
session()->flash('success','Inserted Successfully');
}
}
backend/departments.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Departments</title>
@livewireStyles
</head>
<body>
<div class="container">
@livewire('departments')
</div>
@livewireScripts
</body>
</html>
livewire/departments.blade.php
<div>
@if(Session::has('success'))
<span style="color: green;font-weight: bold;"> {{Session::get('success')}} </span>
@endif
<form wire:submit.prevent="save">
<input type="file" wire:model="photo">
@if ($photo)
<img src="{{ $photo->temporaryUrl() }}" width="100">
@endif
@error('photo') <span class="error">{{ $message }}</span> @enderror
<input type="text" placeholder="name" wire:model="name">
<input type="text" placeholder="content" wire:model="content">
<button type="submit">Save Photo</button>
</form>
</div>
Route
web.php
Route::view('departments','backend.departments');
No comments