laravel 上的图像更新和删除旧图像

Image update and remove old image on laravel

尝试在我的更新控制器中实现更新文章,它似乎有效,但问题是当我只想更新 post 而不上传图像时,旧的总是被删除,这是不应该的。

这是我的商店功能

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();
        }
    }

好的,因为我在我的控制器中使用了模型绑定,所以我不需要找到 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,
            ]);
        }
}

试试这个

private function storeImage($post)
{

    if (request()->hasFile('image')){
        $image_path = "/storage/".'prev_img_name';  // prev image path
        if(File::exists($image_path)) {
            File::delete($image_path);
        }
        $post->update([
           'image' => request()->image->store('uploads', 'public'),
        ]);

        $image = Image::make(public_path('storage/'.$post->image))->fit(750, 300);
        $image->save();
    }
}

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

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