Search code examples
phplaravelfunctioncontrollerlaravel-10

Trying to write a function that if product exists, then specific category cannot be deleted


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

    }

Solution

  • You need to modify it like that:

    public function destroy(string $id)
    {
        $category=Category::findOrFail($id);
        if(count($category['products'] == 0))
        {
            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!');
        }
    
    }
    

    OR you can do it like this if you want to involve Products model with that:

    public function destroy(string $id)
    {
        $category=Category::findOrFail($id);
        $product = Product::where('category_id', $category['id'])->first();
        if(!$product)
        {
            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!');
        }
    
    }