webfuelcode's avatar

If statement inlivewire for image

Laravel 10 with breeze, I want to add profile image. How to make this function fit in livewire form... Just checking if the image is there, if so delete it and update the profile.

if ($request->hasFile('image')) {
            $oldfile = public_path('images/user_img/') . $user->image;
            $filename = 'image' . '_' .time() . '.' . $request->file('image')->getClientOriginalExtension();
            if(File::exists($oldfile)){
                File::delete($oldfile);
            }

            $request->file('image')->storeAs('user_img', $filename, 'public');

            $validatedData['image'] = $filename;
        }
0 likes
1 reply
azimidev's avatar

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.

Please or to participate in this conversation.