This Laravel-based PHP function provides a recursive solution to create a hierarchical structure of categories,
allowing for unlimited levels of subcategories. It's a valuable tool for organizing and displaying data in web applications

Define PHP Function
if (! function_exists ('fetchCategoryTree')){
function fetchCategoryTree ($parent = 0, $spacing = '', $cat_tree_array = array()) {
$cats = DB::select('select id,name from categories where parent_id = ?', [$parent]);
foreach ($cats as $cat) {
$cat_tree_array[] = array("id" => $cat->id, "name" => $spacing . $cat->name);
$cat_tree_array = fetchCategoryTree($cat->id, $spacing . ' ', $cat_tree_array);
}
return $cat_tree_array;
}
}
Calling Function in Blade File
@foreach (fetchCategoryTree() as $cat)
<option value="{{ $cat['id'] }}" >{{ $cat['name'] }}</option>
@endforeach