Search code examples
laravelfilestorageunlink

Old File from storage is not being deleted on update Laravel


I am trying to delete the existing image from the storage while the new image is being updated. But everytime the new image is inserted retaining the previous ones.

When I dd the image from database to unlink, I get full url i.e.

http://127.0.0.1:8000/teacger-image/1598097262-85508.jpg

While only teacher-image/1598097262-85508.jpg has been stored in the database.

Function to delete the image

public function deleteImageFromStorage($value)
{
    if (!empty($value)) {
        File::delete('public/' . $value);
    }
}

I have called the method in the controller when there is image posted during update.

update method includes

 if ($request->hasFile('image')) {
            $teacher->deleteImageFromStorage($teacher->image);
            $file = $request->file('image');
            $filename =  time() . '-' . mt_rand(0, 100000) . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('teacher-image', $filename);
            $teacher->image = $path;
        }

Also I have used Storage::delete() and unlink as well but none of them seem to work.

help


Solution

  • I had to do this to solve my problem. The url was being taken by the configuration set on filesystems.php under config file.

    public function deleteImageFromStorage($value)
    {
        $path_explode = explode('/', (parse_url($value))['path']); //breaking the full url 
        $path_array = [];
        array_push($path_array, $path_explode[2], $path_explode[3]); // storing the value of path_explode 2 and 3 in path_array array
        $old_image = implode('/', $path_array);
    
        if ($old_image) {
            Storage::delete($old_image);
        }
    }
    

    If someone goes through the same problem in the future, this might be helpful.