laravelfilefacade

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');

    }

Solution

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

    This is the root directory.

    If we assume:

    ... then:

    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');
    
        }