cyberkid
cyberkid

Reputation: 61

How to keep old image if a new one isn't uploaded on update. Laravel

I am hoping someone here will be able to help with this;

When a post is being updated in my project, I'd like for the image file that was uploaded during the initial post creation time, to be the same, if I don't want to upload a new one during an update.

**Also, if I do upload a new one during the update, I'd like for it to replace the old one. So, the old one gets deleted.

Here's what I currently have for the initial creation of posts;

if ($request->hasFile('post_avatar')){
        $postimg = $request->file('post_avatar');
        $postImgName = Str::slug($request->post_title) . '.' . $postimg->getClientOriginalExtension();
        $destinationPath = public_path('/postImages');
        $imagePath = $destinationPath. "/". $postImgName;
        $postimg->move($destinationPath, $postImgName);
        $post->post_avatar = $postImgName;
 }

Thanks in advance!

Upvotes: 0

Views: 410

Answers (2)

bhucho
bhucho

Reputation: 3420

I am assuming that you keep the name saved for the old image,
You can do like this,

$post_image = Str::slug($post->post_title); // taking from your old Post model instance lets say $post = Post::find(%id);

if ($request->hasFile('post_avatar')){
        $image_path = public_path("/postImages/".$post_image);
        if (File::exists($image_path)) {
            File::delete($image_path);
        }
        $postimg = $request->file('post_avatar');
        $postImgName = Str::slug($request->post_title) . '.' . $postimg->getClientOriginalExtension();
        $destinationPath = public_path('/postImages');
        $imagePath = $destinationPath. "/". $postImgName;
        $postimg->move($destinationPath, $postImgName);
        $post->post_avatar = $postImgName;
 } else{
        $post->post_avatar = $post_image;
}
  $post->save();

Edit :

$post_image = Str::slug($post->post_title);

to

$post_image = $post->post_title;

Upvotes: 0

fakorede
fakorede

Reputation: 783

Alright, below is the workflow for achieving what you have asked in your question. While, I'm not providing all the code, I believe this will be sufficient enough to guide you.

public function update(Request $request, $id)
    {

        $post = Post::findOrFail($id);

        if ($request->hasFile('post_avatar')) {
            $postimg = $request->file('post_avatar');

            if ($post->post_avatar) {
                // delete old image
                // save new image
            } else {
                // save new image
            }
        }

        // save post and redirect
    }

Upvotes: 0

Related Questions