当用户在发布前更新他/她的帖子时,我目前正在尝试删除图像。
一切工作正常,图像在数据库和帖子页面中发生了变化,但我想删除以前的图像。
这是我的控制器
public function updatePost(Request $request){
$data = $request->all();
$postid = $request['id'];
$isExist = Post::where('id', $postid)->first();
if($isExist){
if ($request->hasFile('image')) {
$file = $request->File('image');
//Get filename with extension
$fileNameToStoreWithExt = $file[0]->getClientOriginalName();
//Get just filename
$filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
//Get just ext
$extension = $file[0]->getClientOriginalExtension();
//File to store
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
//Upload Image
$path = $file[0]->storeAs('image', $fileNameToStore);
$file[0]->move('storage/image', $fileNameToStore);
File::delete(public_path('storage/image'.$isExist['image']));
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content'],
'image' => $path
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}else{
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content']
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}
}else{
return response()->json([
'error'=> 'post does not exist'
]);
}
}
我使用了:
File::delete(public_path('storage/image'.$isExist['image']));
但没起到作用
我的删除功能
public function deletePost($id){
$post = Post::where('id',$id)->first();
// dd($post);
if(!$post){
return response()->json([
'status' => '500',
'error' => 'post not found'
]);
}
Storage::disk('public')->delete('/storage/image'. $post['image']);
Post::where('id', $id)->delete();
return response()->json([
'status'=> '200',
'response'=> 'Post successfully deleted'
]);
}
我的存储路径snapshotx 1c 0d1x
6条答案
按热度按时间dwthyt8l1#
请参考链接https://laravel.com/docs/6.x/filesystem
lsmepo6l2#
如果你查看laravel文件系统文档,你会发现laravel支持多个磁盘。
公共目录的路径应该是这样的。
e5nszbig3#
它很容易做一个if语句,并删除旧的图像更新!这段代码是一个例子,编辑它到您的要求。
另一个:
标签:https://laracasts.com/discuss/channels/laravel/delete-old-image-from-public-folder-after-updating
l2osamch4#
你可以使用普通的PHP删除文件关键字@unlink
axzmvihb5#
您可以使用
File
从特定路径删除文件Delete uploaded file from public dir
或
您可以使用
unlink
进行相同的PHP -> unlink
oxf4rvwz6#
unlink('image_Name');
这个工作与我。