【问题标题】:How to use Storage facade to delete a file如何使用 Storage 门面删除文件
【发布时间】:2021-11-11 17:58:12
【问题描述】:

当我使用 php unlink 方法时,我可以使用以下逻辑从本地驱动程序中删除图像,但是当我使用 Storage 门面时,帖子被删除但图像没有被删除。我尝试过使用 Facade 方式,但似乎无法正常工作。我错过了什么?

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

    }

【问题讨论】:

  • 不要在删除方法中传递storage/。存储门面 ID 自动使用 storage 目录中的文件。
  • 我在通过 storage/ 之前尝试了 Storage::delete($post->imagePath);,但效果不佳。

标签: laravel file facade


【解决方案1】:

您必须了解(默认情况下)Storage 外观会查看 /your/project/storage/app

这是root 目录。

如果我们假设:

  • 您的项目位于/home/alphy/my-project
  • $post->imagePath == 'posts/18/picture.png'

...然后:

  • 所有Storage门面方法,包括delete()copy()path()...当你给他们$post->imagePath时会寻找/home/alphy/my-project/storage/app/posts/18/picture.png

所以:

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

    }

【讨论】:

  • 有道理,我的图像在 ``` /home/alphy/my-project/storage/app/public/postImages/uniqueIdofTheImage``` my $post->imagePathpostImages/uniqueIdofTheImage 任何想法如何解决它或如何覆盖默认路径?
  • 一切都在config/filesystem.php 中配置。但是,如果图像在storage/app/public,那么你可以简单地做Storage::disk('public')->delete('postImages/uniqueIdofTheImage')
  • 工作,现在我都清楚了...谢谢!
猜你喜欢
  • 2023-04-11
  • 2017-10-21
  • 2015-05-11
  • 1970-01-01
  • 2019-01-16
  • 2015-12-19
  • 1970-01-01
  • 2019-11-24
相关资源
最近更新 更多