如何在Laravel中通过新图像更新时从文件夹中删除以前的图像



**我想删除保存在文件夹中的上一个图像,并在laravel中更新新图像。这段代码有什么错误?它不起作用**xxxxxxxxxxxxxxxxxxxxxxx

存储数据和图像的代码

public function store(Request $request)
{
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename  = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->image->move(public_path('/uploads/image'), $fileNameToStore);
}
else
{
$fileNameToStore = 'No Img Found!';
}
$covidrecord = new Covidrecord();
$covidrecord->fullname = $request->fullame;
$covidrecord->image = $fileNameToStore;
$covidrecord->save();
if( $covidrecord->save())
{
return redirect()->route('store')->with(['msg'=>"User create successfully"]);
return redirect()->route('store')->withError(['msg'=>"User cannot be registerd at the moment"]);
}
}

更新数据和图像的代码

public function update(Request $request, $id)
{
$covidrecord = Covidrecord::find($id);
#Check if uploaded file already exist in Folder
if($request->hasFile('product_image'))
{
#Get Image Path from Folder
$path = 'uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}
#If File is new and not Exist in Folder
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename  = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->product_image->move(public_path('/uploads/image'), $fileNameToStore);
$covidrecord->product_image = $fileNameToStore;
if($covidrecord->save())
{
dd('Product updated Successfully');
}
else{
dd('Product update Failed');
}
}
}

文件中有红线

在更新方法中生成检查文件存在的路径时,缺少公共路径方法

$path = public_path().'/uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}

最新更新