skip to Main Content

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


  1. 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 the store() method. So, to delete the file, you can use the following code:

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

    This will delete the file with the given file name from the public disk.

    Login or Signup to reply.
  2. There are multiple ways to do this.

    Ensure your file is stored in storage or public. If the public use public_path() if storage use storage_path()

    File Delete

    $deletedFile = File::delete(storage_path('file_name'));
    

    unlink method

    $filedeleted = unlink(public_path('file_name'));
    

    Always use file_exists before performing the deleting action.

    if (file_exists( storage_path('file_name') )){}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search