Neeraj1005's avatar

photo update, removing previous/old photo

In my laravel project for uploading the file I'm using the spatie media library package. But using this I'm facing the problem with updating the image. Basically for updating the image, when I upload the new image I want to remove old or previous image if post having the image. But in case it store as new image. can anyone knows how to do this update image and remove previous image using spatie media lib pkg? This is my update method

  public function update(PostStoreRequest $request, Post $post)
    {
        $input = $request->validated();

        $post->update($input);

        $post->tags()->sync(request('tags'));

        if($request->hasFile('featuredimage')){
            $post->addMedia($request->featuredimage)->toMediaCollection('posts');
        }

        return redirect(route('posts.index'))->withInfo('Posts updated succesfully');
    }
0 likes
1 reply
automica's avatar

@neeraj1005 just before you add the new media file get the existing image. When you’ve added the new media file do something like the following:

$image_path = "/images/filename.ext"; // Value is not URL but directory file path if(File::exists($image_path)) { File::delete($image_path); }

Please or to participate in this conversation.