Tobi Ferdinand
Tobi Ferdinand

Reputation: 137

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload

public function updateProfileImage(Request $request)
    {
        $user = auth('api')->user();

        $image = $request->input('image'); // image base64 encoded
        preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
        $image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
        $image = str_replace(' ', '+', $image);
        $imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
            'profilePicture' => $imageName
        ]);

        return [
            //'Message' => "Success",
            'profilePhoto' => $user['profilePicture']
        ];

    }

How can i delete the old picture from the directory after new one has been uploaded.

Upvotes: 0

Views: 78

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:

$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
    'profilePicture' => $imageName
]);

Storage::disk('public')->delete($oldImage);

return [
    //'Message' => "Success",
    'profilePhoto' => $user['profilePicture']
];

PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

Upvotes: 1

Related Questions