monstajamss's avatar

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.

0 likes
4 replies
deepu07's avatar

@monstajamss save image name with user_name or id and when you're uploading new pic jus replace the old image.

jlrdw's avatar

You can unlink just prior to saving the new one. See the laravel files ystem in the docs.

sevenTopo's avatar

you can use unlink($file) "php function ":

unlink('/path/to/your/uploads/folder/here/'.$image_name);

drewdan's avatar

We use a model observer, so whenever the model is updating, we check to see if the image has changed and then we tell laravel to delete the old one.

Please or to participate in this conversation.