如何在更新 Laravel 8 中的图像后从 Public 中的文件夹中删除图像

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

我试图更新一个包含文件(图像)的表单并删除旧图像。更新工作正常,但旧图像无法删除。我试过这段代码,但图像没有被删除。请帮我。提前致谢。

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');
}

您可以像这样删除旧图像,如果图像不在存储的根目录中,请在图像名称之前插入存储中的文件位置。

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');
}