Laravel 8 E-Commerce - Problem of Product Image Deletion and Their Solution
In this video, we will explore the problem of product image deletion and provide a solution.
First, let's identify the problem.
Login with admin credentials and navigate to the products page.
Delete any product, but before doing so, let's check the image in the project directory.
To do this, we need to get the product image name.
Open phpMyAdmin and access the database.
Browse the products table and find the product image name.
Copy the image name and navigate to the project directory, then public/assets/images/products.
Search for the image by pasting the product image name and hitting enter.
You should see the product image.
Now, delete the product by clicking on the delete button.
The product has been deleted, but the image still exists.
This means that the product has been removed, but the image has not been deleted.
To delete the product image while deleting the product, we need to add some code to the deleteProduct method.
Open the AdminProductComponent.php class file and make the following changes:
public function deleteProduct($id)
{
$product = Product::find($id);
if($product->image)
{
unlink('assets/images/products'.'/'.$product->image);
}
if($product->images)
{
$images = explode(",",$product->images);
foreach($images as $image)
{
if($image)
{
unlink('assets/images/products'.'/'.$image);
}
}
}
$product->delete();
session()->flash('message','Product has been deleted successfully!');
}
Save the changes and let's check again.
Refresh the page and delete another product.
Copy the image name and navigate to the product directory.
Search for the image and verify that it exists.
Delete the product and check the image directory again.
This time, the product image should be deleted.
By following these steps, you can solve the image deletion problem.