monstajamss's avatar

Remove Old Picture or file uploaded using unlink

I have a file upload on my website and i am trying to removed the previous picture when i upload a new one.

I have this in my controller

  $user = User::find(auth()->user()->id);
        $path = ('avatars/'.$user->username);
        if(file_exists($path)){
            @unlink($path);
        }
        $user->update([
            'avatar' => $this->avatar->store($path, 'wasabi'),
        ]);

How do i do this please?

0 likes
8 replies
Sinnbeck's avatar

I would not assume this gives you the correct path

$path = ('avatars/'.$user->username);

where is the file placed?

Storage::disk('public')->delete('avatars/'.$user->username);

Like this perhaps ?

1 like
monstajamss's avatar

@Sinnbeck So i did this

 $user = User::find(auth()->user()->id);
        $path = ('avatars/'.$user->username);
        $oldPath = ('https://s3.eu-west-1.wasabisys.com/sample-bucket/'.$user->avatar);
        // dd($oldPath);
        if(Storage::disk('wasabi')->exists($oldPath)){
            Storage::disk('wasabi')->delete($oldPath);
        }
        $user->update([
            'avatar' => $this->avatar->store($path, 'wasabi'),
        ]);

But still it doesn't work

tykus's avatar

@monstajamss out of interest, what do you think auth()->user() gives you? An Eloquent query is unnecessary!

monstajamss's avatar

@tykus so basically i am trying to get the old image from the database, check if it exists . Then remove old one and update it with new one

Snapey's avatar
Snapey
Best Answer
Level 122

If you use storage::disk you need to provide the path relative to the bucket specified by that disk, and not the whole URL..

        if(Storage::disk('wasabi')->exists($user->avatar)){
            Storage::disk('wasabi')->delete($user->avatar);
        }
1 like

Please or to participate in this conversation.