【发布时间】:2019-09-17 05:50:15
【问题描述】:
这仍然与我在这里How to remove and unlink multiple images in json format的帖子有关
我可以存储和删除所有多个图像。但是更新和删除旧图像时我仍然有问题。更新新图像时,我的代码仍然没有删除旧图像。
我的更新控制器,我使用 handlerequest 方法来存储图像,其中 oldImage 是数据库中的变量,它将与新图像进行比较。如果不一样,则删除旧图像。
public function update(Requests\UpdatePostRequest $request, $id)
{
$post = Post::findOrFail($id);
$oldImage = $post->image;
$data = $this->handleRequest($request);
$post->update($data);
if($oldImage != $post->image)
{
foreach (json_decode($post->image, true) as $oldImage) {
$this->removeImage($oldImage);
}
}
if($request->submitbutton =='Publish')
{
Alert::success('Your post was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
if($request->submitbutton =='Save Draft')
{
Alert::success('Your draft was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
}
我的handlerequest 方法来存储多个图像,这个方法是使用store 方法工作的。所以这个问题不在这里。
private function handleRequest($request)
{
$data = $request->all();
if($request->hasFile('image'))
{
$images = $request->file('image');
foreach($images as $key=>$image){
$fileName = $image->getClientOriginalName();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
if($successUploaded)
{
$width = config('cms_blog.image.thumbnail.width');
$height = config('cms_blog.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make($destination . '/' . $fileName)
->resize($width,$height)
->save($destination . '/' . $thumbnail);
$datax[] = $fileName;
}
$data['image'] = json_encode($datax);
}
}
return $data;
}
删除方法
public function removeImage($image)
{
if( ! empty($image))
{
$imagePath = $this->uploadPath . '/' . $image;
$ext = substr(strrchr($image, '.'), 1);
$thumbnail = str_replace(".{$ext}", "_thumb.{$ext}", $image);
$thumbnailPath = $this->uploadPath . '/' . $thumbnail;
if(file_exists($imagePath) ) unlink($imagePath);
if(file_exists($thumbnailPath) ) unlink($thumbnailPath);
}
}
如何解决我的问题,以便在旧图像与新图像不同时删除旧图像?
【问题讨论】: