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');
}
CodePudding user response:
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');
}
CodePudding user response:
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));