webfuelcode's avatar

How to check and delete image from a post on updating

I am just trying to clear the storage by deleting unused images the post has, whenever the post is updated.

public function update(Request $request, Post $post)
    {
        $validated = $this->validate($request, [
            'title' => 'required',
            'img1' => 'sometimes|image',
            'category_id' => 'required',
            'description' => 'required'
        ]);

        // Post image upload
        if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            if(__________){
                Storage::disk('my_files')->delete('post_img/' . __________);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }

        $post->update($validated);
        return redirect()->route('post.show', $post->slug)->withMessage('Updated successfully!');
    }

Main part here is, I am not able to make it delete.

// Post image upload
        if($request->hasFile('img1')){
            $filename = time() . '.' . $request->img1->getClientOriginalExtension();
            if(_________){
                Storage::disk('my_files')->delete('post_img/' . _________);
            }
            $request->img1->storeAs('post_img', $filename, 'my_files');
            
            $validated['img1'] = $filename;
        }

if(__________){ Storage::disk('my_files')->delete('post_img/' . __________); } How to check if the post has an image file, and then delete it if the user uploads a new one.

0 likes
1 reply
tisuchi's avatar

@webfuelcode have you tried this way?

public function update(Request $request, Post $post)
{
    $validated = $this->validate($request, [
        'title' => 'required',
        'img1' => 'sometimes|image',
        'category_id' => 'required',
        'description' => 'required'
    ]);

    // Post image upload
    if($request->hasFile('img1')){
        $filename = time() . '.' . $request->img1->getClientOriginalExtension();
        
        // Check if you have any attached image with the post.
        if($post->img1 !== null){
        	// You may need to adjust image path, if required.
            $image_path = "/images/$post->img1";
			
			if(File::exists($image_path)) {
			    File::delete($image_path);
			}
        }

        $request->img1->storeAs('post_img', $filename, 'my_files');
        $validated['img1'] = $filename;
    }

    $post->update($validated);
    return redirect()->route('post.show', $post->slug)->withMessage('Updated successfully!');
}

Please or to participate in this conversation.