php - Laravel 上的图像更新并删除旧图像

标签 php laravel-5.8

尝试在我的更新 Controller 中实现更新文章似乎可行,但问题是当我只想更新帖子而不上传图像时,旧的总是会被删除,但这是不应该的。

这是我的商店功能

public function store(Post $post)
{
        $post->update($this->validateRequest());
          
        $this->storeImage($post);
        

        return redirect('post/'.$post->id)->with('success', 'New ariticle has been posted');
    }

} 

这是我的验证

private function validateRequest()
    {
        return request()->validate([
            'title'=> 'required',
            'content' => 'required',
            'image' => 'sometimes|image|max:5000',

        ]);
    }

这是我的更新函数

public function update(Post $post)
{
        File::delete(public_path('storage/'.$post->image)); 
        $post->update($this->validateRequest());
          
        $this->storeImage($post);
        

        return redirect('post/'.$post->id)->with('success', 'This post has 
        been Edited');
    }

} 

我尝试将 File::delete 添加到我的 storeImage 函数中并将其从我的更新函数中删除,它解决了问题,但旧图像并未从目录中删除

private function storeImage($post)
{
  
  if (request()->has('image')){
  File::delete(public_path('storage/'.$post->image))
  $post->update([
       'image' => request()->image->store('uploads', 'public'),
  ]);
  
  $image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
  $image->save();
        }
    }

好吧,因为我在 Controller 中使用模型绑定(bind),所以我不必找到 id,对吗? 所以我改变了我的更新函数,这基本上是 Akhtar munir 建议的,结果是这样的。图像更新工作正常,当我更新它时它也会删除旧图像。但是我发现了另一个问题,问题是当我编辑文章和标题时它没有像我更新时那样改变,我希望你能看看这是正确的吗?

public function update(Post $post){
    $this->validateRequest();
    if(request()->hasFile('image') && request('image') != ''){
            $imagePath = public_path('storage/'.$post->image);
            if(File::exists($imagePath)){
                unlink($imagePath);
            }
            $image = request()->file('image')->store('uploads', 'public');
            $post->update([
                'title' => request()->title,
                'content' => request()->content,
                'image' => $image,
            ]);
        }
}

最佳答案

这是我在我的方法之一中所做的。它可能对你有帮助。

public function update(Request $request, $id)
{
    if (UserDocument::where('id',$id)->exists()) {

        $this->validateUserDocument($request);
        
        if ($request->hasFile('doc_file') && $request->doc_file != '') {
            
            $doc = UserDocument::where('id',$id)->first();
            // dd($doc);
            $file_path = storage_path().'/app/'.$doc['doc_file'];
            //You can also check existance of the file in storage.
            if(Storage::exists($file_path)) {
               unlink($file_path); //delete from storage
               // Storage::delete($file_path); //Or you can do it as well
            }

            $file = $request->file('doc_file')->store('documents'); //new file path

            $doc->update([
                'title' => $request->title,
                'doc_file' => $file //new file path updated
            ]);

            session()->flash('success','Document updated successfully!');
            return redirect()->route('userdocs');
        }

        session()->flash('error','Empty file can not be updated!');
        return redirect()->back();
    }
    session()->flash('error','Record not found!');
    return redirect()->back();
}

在这段代码中,我只是想向您澄清,我已将图像路径存储在数据库中,首先我检索了该路径,并使用该路径在本地存储中找到了图像,先删除它,然后更新它与新的。但请确保在两种情况下都将图像路径存储在数据库中,当然还有插入和更新。

所以最后你也可以像这样优化你的代码,它会做你期望的同样的事情,无论是图像和所有数据还是只有标题和内容。

public function update(Post $post){
    $this->validateRequest();
    $data = [
        'title' => request()->title,
        'content' => request()->content
    ];
    if (request()->hasFile('image') && request('image') != '') {
        $imagePath = public_path('storage/'.$post->image);
        if(File::exists($imagePath)){
            unlink($imagePath);
        }
        $image = request()->file('image')->store('uploads', 'public');
        $data['image'] = $image;
        //$post->update($data);
    }
    $post->update($data);
}

关于php - Laravel 上的图像更新并删除旧图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57768764/

相关文章:

php - 从 Laravel-5.7 在 S3 中上传文件时出现 AccessDenied 错误

php - 如何从 Google Cloud Storage 提供 SVG 图像?

php - PDO 将默认获取模式设置为 FETCH_UNIQUE

php - MySQL 如果可用数据转到页面并显示结果,如果不可用则返回检查号

php - 使用包含多个值的 XPath 查询

php - 如何在 codeigniter 中获取映射到特定零售商的用户?

Laravel 在提交包含图像和数据的表单时显示必需的错误消息

php - 读取路由函数中的 Blade 变量

php - 如何从 Controller 调用事件?命名空间

laravel - 登录后出现太多重定向错误