Support the ongoing development of Laravel.io →
Eloquent Views

Hello guys, i'm trying to create multi-level dynamic menu compatible with bootstrap3. I have already done display all records, but without children items. I paste my code, maybe someone know how to fix that.

private static function mapTree($dataset, $parent = 0)
{
	$tree = array();

	foreach ($dataset as $id => $node)
	{
		if ($node->parent_id != $parent) continue;
		$node->children = self::mapTree($dataset, $node->id);
		$tree[$id] = $node;
	}

	return $tree;
}


/**
 * GenerateMenu
 */
private static function prepareMenu($tree)
{
	$data = '<ul class="nav navbar-nav">';

	foreach ($tree as $item)
	{
		$data .= '<li><a href="' . $item->url . '">' . $item->title . '</a></li>';

		if (count($item->children) > 0)
		{
			self::prepareMenu($item->children);
		}
	}

	$data .= '</ul>';

	return $data;
}

/**
 * Create menu
 */
public static function generateMenu()
{
	$urls = parent::all();
	$tree = self::mapTree($urls);
	$data = self::prepareMenu($tree);

	return $data;
}
Last updated 3 years ago.
0

You can try this code

private static function prepareMenu($tree)
{
    $data = '<ul class="nav navbar-nav">';

    foreach ($tree as $item)
    {
        $data .= '<li><a href="' . $item->url . '">' . $item->title . '</a></li>';

        if (count($item->children) > 0)
        {
            $data .= self::prepareMenu($item->children);
        }
    }

    $data .= '</ul>';

    return $data;
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Delavor delavor Joined 15 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.