laravel 7 update image and delete old image code example

Example 1: when image update laravel delete remove image

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

Example 2: when image update laravel delete remove image

public function update($id)
{
      $article = Article::find($id);
    
    if(Input::hasFile('image'))
    {
             $file = Input::file('image');
             $name = time() . '-' . $file->getClientOriginalName();
             $file = $file->move(public_path() . '/images/profile/', $name);
             $article->file= $name;
    }
    $article->save();
    return "success";
}

Tags:

Php Example