How to use Storage facade to delete a file

I’m able to delete the image from the local driver using the below logic when I use php unlink method but when I use Storage facade the post get’s deleted but the image is not deleted. I’ve tried playing around with the Facade way but I can’t seem to have it work. What I’m I missing?

public function destroy(Post $post)
    {
        // unlink('storage/'.$post->imagePath);
        Storage::delete('storage/'.$post->imagePath);
        $post->delete();
        return redirect(route('posts.index'))->with('flash', 'Post Deleted Successfully');

    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have to understand that (by default), the Storage facade looks into /your/project/storage/app.

This is the root directory.

If we assume:

  • Your project is located in /home/alphy/my-project
  • $post->imagePath == 'posts/18/picture.png'

… then:

  • All Storage facade methods, including delete(), copy(), path()… will looks for /home/alphy/my-project/storage/app/posts/18/picture.png when you give them $post->imagePath

So:

    public function destroy(Post $post)
    {
        Storage::delete('storage/'.$post->imagePath);
        // tries to delete /home/alphy/my-project/storage/app/storage/$post->imagePath     
        // which is probably wrong   


        $post->delete();
        return redirect(route('posts.index'))->with('flash', 'Post Deleted Successfully');

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x