First, ensure your Livewire component is set up to handle file uploads. Livewire has a file upload system that works with temporary uploaded files.
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class UserProfile extends Component
{
use WithFileUploads;
public $image;
public function render()
{
return view('livewire.user-profile');
}
public function save()
{
$user = auth()->user(); // Or however you get your user
if ($this->image) {
$oldfile = public_path('images/user_img/') . $user->image;
if (File::exists($oldfile)) {
File::delete($oldfile);
}
$filename = 'image_' . time() . '.' . $this->image->getClientOriginalExtension();
$this->image->storeAs('user_img', $filename, 'public');
$user->update(['image' => $filename]);
}
// Additional logic for saving other profile data
}
}
Your Livewire component's view should include a file input and a submit button. Livewire will automatically handle the file upload when the form is submitted.
In Your Livewire View (e.g., resources/views/livewire/user-profile.blade.php):
<form wire:submit.prevent="save">
<input type="file" wire:model="image">
@error('image') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Save Profile</button>
</form>
Make sure to configure your file system correctly in config/filesystems.php for storing the images. Since you're using the public disk in your example, ensure it's properly set up.