Skip to content

Instantly share code, notes, and snippets.

@daugaard47
Created August 18, 2020 04:48
Show Gist options
  • Save daugaard47/659984245d31b895d00ee5dcbdee44ec to your computer and use it in GitHub Desktop.
Save daugaard47/659984245d31b895d00ee5dcbdee44ec to your computer and use it in GitHub Desktop.
Upload images with Livewire and compress with Intervention Image.
//HTML
<div class="avatar-file">
<label class = "text-bh-navy-500">Choose Image</label>
<input type = "file" wire:model = "avatar">
</div>
//LW Component
use WithFileUploads;
public $avatar;
public function submitProfileUpdate() {
$data = $this->validate([
'first_name' => 'required',
'last_name' => 'required',
'avatar' => 'nullable|image|max:2048', // 2MB Max
]);
$image = $this->avatar;
$avatarName = $this->first_name . '-' . $this->last_name . '-' . substr(uniqid(rand(), true), 8, 8) . '.' . $image->getClientOriginalExtension();
$img = Image::make($image->getRealPath())->encode('jpg', 65)->fit(760, null, function ($c) {
$c->aspectRatio();
$c->upsize();
});
$img->stream(); // <-- Key point
Storage::disk('local')->put('public/images/avatars' . '/' . $avatarName, $img, 'public');
//SAVE FILE NAME TO DB
$userUpdate = Auth::user()->update([
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'avatar' => $avatarName,
]);
@anselmelly
Copy link

anselmelly commented Feb 7, 2021

Your are a life saver.. Thanks for this

@diegoglz-dev
Copy link

It worked for me. Thanks for sharing!!!

@robgreenn
Copy link

Thank you very much, it helped a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment