In my controller, I store images in my public folder like this:
//...
$fileName = $request->all()["image"]->store("/images", "public");
$user->image_url = Storage::url($fileName);
$user->save();
Now, When a user wants to change their profile pic, I want to delete the image:
// $user->image_url looks like: /storage/images/ZVw3jm8Y4k2mx59DGouz.jpg
Storage::delete($user->image_url, "public");
But the above code is not deleting the image. Please, what is the right way?
2
Answers
The
Storage::delete()
method expects the file path relative to the storage disk root, not the public URL. In this case, the file path is the second argument passed to thestore()
method. So, to delete the file, you can use the following code:This will delete the file with the given file name from the public disk.
There are multiple ways to do this.
File Delete
unlink
methodAlways use
file_exists
before performing the deleting action.