sumitgroup
1 month ago
213
11
Laravel

How i can Delete previous image when update in Laravel 6?

Posted 1 month ago by sumitgroup

Hi All, I am trying to update new images, but when i edit my form and select new image then previous image not deleting from my folder, Please let me know where i am mistaking. Here are my image update data...

public function update(Request $request, $builder)
{
$bld = Builder::findOrFail($builder);
$chr  = substr($request->bname, 0, 1);
        if( $request->hasFile('bllogo')){ 
    $thums= $request->bllogo;
        $bllogo = uniqid($chr).'.'.$thums->getClientOriginalExtension();
        $img = Image::make($thums->getRealPath());
        $img->resize(300, null, function ($constraint) {
            $constraint->aspectRatio();          
        });
        $thumbPath = public_path().'/builders_img/'.$bllogo;
         if (file_exists($thumbPath)) { // unlink or remove previous image from folder
            unlink($thumbPath);
        }
 $img->save($thumbPath);
        $optimizerChain = OptimizerChainFactory::create();
        $optimizerChain->optimize($thumbPath);
        $bllogoimg = $bllogo;

    }else{
        $bllogoimg = NULL;
    }
    $bld->name =$request->bname;
    $bld->slug =$request->bslug;
    $bld->title =$request->metatitle;
    $bld->short_desc =$request->metadesc;
    $bld->meta_desc =$request->metadesc;
    $bld->keyword =$request->metakeyword;
    $bld->bldlogo =$bllogoimg;
    $bld->save();
    return response()->json(['status'=>1], 201);
}

Please sign in or create an account to participate in this conversation.