I programmed a product registration and together with it, I upload an image. This image is saved to public / storage / products. There is an input field that is to put the name of the image and the image is given this name and that name is saved in the database along with the image extension. I want to know how I delete this image from the public / storage / products folder when I click remove.
The method I tried below, didn't work Controller:
public function store(Request $request)
{
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $nameFile;
$product->save();
return redirect()->route('ProductControllerIndex');
}
public function destroy($id)
{
$products = Product::all();
$filePathName = 'products/' . $products->imageName;
if( file_exists($filePathName) ){
unlink($filePathName);
}
// $delete = Product::find($id);
// if(!$delete)
// return redirect()->route('ProductControllerCreate');
// $delete->delete();
// return redirect()->route('ProductControllerCreate');
}
}
view:
<form action="{{ route('ProductControllerDestroy', $product->id) }}" method="post">
@csrf
@method('DELETE')
<input type="submit" value="Remover">
</form>