简体   繁体   中英

How to Delete Images from a folder in Public after update of the image in Laravel 8

I tried to update a form including a file(image) and to have the old image deleted. The update works fine but the old image is unable to delete. I tried this code but the image is not deleted. Please, help me. Thanks in advance.

public function update(Request $request, $id)
{
    $slug   = SlugService::createSlug(Category::class, 'slug', $request->title);
    $request->validate([
        'title'=>'required',
        'category_image'=>'image'
    ]);
    if ($request->hasFile('category_image')) {
        $image          = $request->file('category_image');
        $newImageName   = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
        $location       = public_path('/categoryImage');
        $OldImage       = public_path('categoryImage/'.$request->category_image);
        $image->move($location, $newImageName);
        Storage::delete($OldImage);
    }else {
        $newImageName   = $request->category_image;
    }
    Category::where('id', $id)->update([
       'slug'=>$slug,
       'title'=>$request->input('title'),
       'details'=>$request->input('details'),
       'category_image'=>$newImageName
    ]);
    return redirect('category')->with('success', 'Category Successfully Updated');
}

You can delete old image like this, if image is not in root of your storage insert your file location inside storage before image name.

unlink(storage_path('/location_inside_storage/'.$OldImage));

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

$category = Category::find($id); #new

if ($request->hasFile('category_image')) {
    $image          = $request->file('category_image');
    $newImageName   = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
    $location       = public_path('/categoryImage');
    $OldImage       = public_path('categoryImage/'.$category->category_image); #new
    $image->move($location, $newImageName);
    unlink($OldImage); #new
}else {
    $newImageName   = $request->category_image;
}

#you can simplify this as
$category->slug = $slug;
$category->title = $request->title;
$category->details = $request->details;
$category->category_image = $newImageName;
$category->save()

return redirect('category')->with('success', 'Category Successfully Updated');

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM