Remove categories with all childs derived from parent category



PHP Snippet 1:

foreach ($categories as $category) {

PHP Snippet 2:

$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');

PHP Snippet 3:

if (!function_exists('CategoryTree')) {
    function CategoryTree($categories = []) {
        $categories = (new Category())->whereIn('parent_id', $categories)->get()->toArray();
        if(count($categories) > 0){
            return array_merge($categories, deleteCategoryTree(array_column($categories, 'id')));
        }
        return $categories;
    }
}

PHP Snippet 4:

(new Category())->whereIn('id', array_column($categories, 'id'))->delete();