Php Laravel8API:更新帖子时从文件夹中删除文件
我有posts表,我上传了它的图像,所以在Php Laravel8API:更新帖子时从文件夹中删除文件,php,laravel,api,file-upload,Php,Laravel,Api,File Upload,我有posts表,我上传了它的图像,所以在update()方法中的PostController()我想编辑post和图像 对于编辑图像,我想从文件夹和数据库中删除最后的图像,并替换新图像 所以我可以从数据库中删除最后的图像,但不能从文件夹中删除它们 控制员: public function update(StorePostRequest $request , $id ) { $validatedData = $request->all(); if
update()
方法中的PostController()
我想编辑post和图像
对于编辑图像,我想从文件夹和数据库中删除最后的图像,并替换新图像
所以我可以从数据库中删除最后的图像,但不能从文件夹中删除它们
控制员:
public function update(StorePostRequest $request , $id )
{
$validatedData = $request->all();
if ($request->hasfile('image')) {
$postTitle = $request->title; //post title for folder name and the images inside it
//delete last Images from database for updating images
Image::where('imageable_type' , 'App\Models\Post')->where('imageable_id' , $id)->delete();
$directory =storage_path().'/images/posts/'.$postTitle;
if($directory){
Storage::disk('public')->deleteDirectory('images/posts/.$postTitle');
}
$files = $request->file('image');
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$postTitle = $request->title; //post title for folder name and the images inside it
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
$image = new Image;
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image; // make an array of uploaded images
}
}
$post = Post::find($id);
$post->category_id = $validatedData['category_id'];
$post->title = $validatedData['title'];
$post->body = $validatedData['body'];
$post->study_time = $validatedData['study_time'];
$post->save();
$post->images()->saveMany($images);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}
帖子和图片之间的关系是:一对多多态,我和邮递员一起品尝
我试过这种方法,但不起作用:
File::delete(public_path('/images/posts/'.$postTitle));
Storage::disk('public')->deleteDirectory($directory);
此外,当我尝试
Storage::disk('public')->deleteDirectory('images/posts/');
它工作正常,posts文件夹已被删除,但问题出在$postTitle
当我使用它时,不起作用您可以使用此代码删除文件
if (!is_dir(public_path('/images/posts/'.$postTitle))) {
mkdir(public_path('/images/posts/'.$postTitle));
}
如果需要删除目录,请使用
Storage::disk('public')->deleteDirectory('images/posts')代码>是否要从“图像”文件夹中删除图像?问题不清楚是的,我编辑了我的问题。。请再次检查错误:取消链接(…/):是一个目录”,您的图像在公用文件夹中的完整路径是什么,我有图像文件夹:public/images/posts/postTitle
。postTitle是文件夹名,帖子的图像在此文件夹中尝试此新代码如果(!Is_dir(public_path('/images/posts/'.$postTitle)){mkdir(public_path('/images/posts/'.$postTitle));}
它不起作用:(感谢它起作用,但只是对于posts文件夹,我想删除posts目录中的postTitle目录,(删除最后一个post图像,而不是所有posts图像)@dumpAndDie,所以只需像u那样在路径的末尾添加一个目录名Storage::disk('public')->deleteDirectory('images/posts/'.$postTitle);
或者我没有得到它?它不工作(无法删除目录)@dumpAndDie idk,刚刚测试过,一切正常。有错误吗?权限吗?可能是您在apache下运行代码,并且拥有错误的文件夹所有者吗?没有问题,因为可以删除posts文件夹。我认为我的方法是错误的,为了更新图像,我必须尝试其他方法删除最后的图像并替换新图像