0

How can I query the categories so that the parent and its related children are displayed in a single row?

Example datatbase:

id   parent_id  name
1        0      Category
2        1      subCat 1
3        2      subsubCat 1
4        0      Category 2
5        3      subCat 2

Code:

public static function getCategories($categories, &$result, $parent_id = 0)
{
    $cats = $categories->filter(function ($item) use ($parent_id) {
        return $item->parent_id == $parent_id;
    });

    foreach ($cats as $cat)
    {
        $result[$cat->id] = $cat->name;
        self::getCategories($categories, $result, $cat->id);
    }

    return $result;
}

public static function index()
{
    $categories = PropertyCategory::select('id', 'parent_id', 'name')->get();
    $result = [];
    return self::getCategories($categories, $result);
}

Example list (This is the layout I would like to achieve):

<div>
  <input type="checkbox" name="scales" value="3" />
  <label for="scales">Category -> subCat 1 -> subsubCat 1</label>
</div>

<div>
  <input type="checkbox" name="scales" value="5" />
  <label for="scales">Category 2 -> subCat 2</label>
</div>
3
  • do you have a max nesting level, like 2 or 3? or can it be anything? Commented Oct 9, 2024 at 9:46
  • It would be great if the depth were unlimited. Commented Oct 9, 2024 at 10:26
  • unlimited depth is not easy, but this is a good discussion of various options with pros and cons stackoverflow.com/questions/4048151/… Commented Oct 9, 2024 at 10:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.