Функция дерева php parrent_id

<?php

namespace App\Services;

use App\Models\CategoryModel;

class CategoryService
{
    
    public function getTree(): array
    {
        $categories = CategoryModel::query()->orderBy('sort_category')
            ->select(['id', 'title', 'slug', 'image','parent_id'])
            ->get()->toArray();
        return $this->generateTree($categories);
    }

    public function generateTree($elements, $parentId = 0): array
    {
        $result = [];
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->generateTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $result[$element['id']] = $element;
                unset($elements[$element['id']]);
            }
        }
        return $result;
    }
}
Shadow