How not to delete Laravel Category if it has products



Image not found!!

Occasionally, we may inadvertently remove a category on our website, leading to errors when there are associated posts. To prevent this issue, it's advisable to implement a conditional check in the code. By incorporating a condition that verifies the presence of posts in a particular category, we can ensure that the category deletion process only proceeds when there are no associated posts. This precautionary measure helps maintain the integrity of the website and prevents potential errors from arising. The solution to this scenario can be found in the provided code below, which addresses the need to safeguard against unintentional category deletions when posts are still linked to them. Implementing this code ensures a smoother user experience and eliminates the risk of encountering errors related to category removal with associated posts.


Here is the code below :

      $post = Post::where('category_id', Input::get('id'))->count();
    if($post > 0){
        return redirect()->route('your route name here where you want to go when post not delete')->with('message', 'Something went wrong');
    }
    else{
        $category= Category::find(Input::get('id'));
        $category->delete();
        return redirect()->route('your route name here where you want to go after deletion')->with('message', 'Category Deleted');
    }