如何使用 Storage facade 删除文件
How to use Storage facade to delete a file
当我使用 php unlink 方法时,我可以使用以下逻辑从本地驱动程序中删除图像,但是当我使用 Storage facade 时,post 被删除但图像没有删除。我尝试过使用 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
门面会查看 /your/project/storage/app
。
这是 root
目录。
如果我们假设:
- 您的项目位于
/home/alphy/my-project
$post->imagePath == 'posts/18/picture.png'
...然后:
- 所有
Storage
外观方法,包括 delete()
、copy()
、path()
... 将在您给它们 [=21] 时查找 /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');
}
当我使用 php unlink 方法时,我可以使用以下逻辑从本地驱动程序中删除图像,但是当我使用 Storage facade 时,post 被删除但图像没有删除。我尝试过使用 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
门面会查看 /your/project/storage/app
。
这是 root
目录。
如果我们假设:
- 您的项目位于
/home/alphy/my-project
$post->imagePath == 'posts/18/picture.png'
...然后:
- 所有
Storage
外观方法,包括delete()
、copy()
、path()
... 将在您给它们 [=21] 时查找/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');
}