gpt4 book ai didi

php - 如何从 laravel 的存储中删除图像?

转载 作者:行者123 更新时间:2023-12-05 08:51:10 24 4
gpt4 key购买 nike

当用户在发布前更新他/她的帖子时,我目前正在尝试删除图片。

一切正常,数据库和帖子页面中的图像已更改,但我想删除以前的图像。

这是我的 Controller

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

我的存储路径快照enter image description here

最佳答案

use Illuminate\Support\Facades\Storage;

Storage::delete('file.jpg'); // delete file from default disk

Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files

Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc

请引用链接https://laravel.com/docs/6.x/filesystem

关于php - 如何从 laravel 的存储中删除图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60313290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com