I’m working on an ecommerce project in Laravel 10.48.8, my PHP version is 8.2.12.
I have used one to many relation to link the parent table categories to one of the child table products using foreign key in delete cascade.
I’ve used resource controller for categories to define a CRUD operation.
Issue: In the destroy function, I’m trying to establish that if a product exists in that specific category, then the category can not be deleted. However, it won’t let me delete other categories as well that do not contain any products. Following is the function that I have written:
P.S. ‘category_id’ is a column in my products table, which is the foreign key used to link the primary key in the category table.
public function destroy(string $id)
{
$category=Category::findOrFail($id);
$product = Product::with('category')->first();
if(!$product->category_id)
{
if(File::exists($category->image))
{
File::delete($category->image);
}
$category->delete();
return redirect()->route('category.index')->with('success','Category deleted successfully');
}
else
{
return redirect()->route('category.index')->with('message','Cannot delete Categories with existing products!');
}
}
2
Answers
Your
Category
model should have relation of categories look like below.and then your destroy function should look like this to achieve what you want by using above relation.
You don’t need to fetch products in this function.
You need to modify it like that:
OR you can do it like this if you want to involve Products model with that: