Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PeterPan's avatar

BAUM package: How to create helper class to render tree in blade

I am looking thru BAUM package for nested sets:

The part that baffled me for a laravel newbie is how to display the tree in blade.template.

The solution from the recursive coding side: https://github.com/etrepat/baum/wiki/Example:-Presenting-a-hierarchy

However, I dont know how to create instantiate the much needed "helper" class so i can call a function inside a blade template.

Can anyone help me on which files that I should modified in order to make this to render correct? I goggled whole day but cannot the solution..

Thanks

0 likes
1 reply
PeterPan's avatar
PeterPan
OP
Best Answer
Level 1

Let me answer my own question..lol. as i finally able to get this to work...woohoo .also to help those that have the same problem as me in the future.

  1. Add a file called helpers.php to your app/ directory. Here i called it as helpers.php.
?php

    function renderNode($node) {
      if( $node->isLeaf() ) {
        return '<li>' . $node->name . '</li>';
      } else {
        $html = '<li>' . $node->name;

        $html .= '<ul>';

        foreach($node->children as $child)
          $html .= renderNode($child);

        $html .= '</ul>';

        $html .= '</li>';
      }

      return $html;
    }
  1. Update your composer.json file with the below.
  "autoload": {
        "classmap": [
            "database"
        ],
         "files" : [
            "app/helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
  1. Then type composer dump-autoload -o

  2. Here at the controller. Here i assume I already have the tables filled up.

Mytree::rebuild(true); //does not return anything hence when dd will get null
        
        
        //dd('end');
        $Mytree = Mytree::all()->toHierarchy();
        return View('testing', ['Mytree' => $Mytree]);

  1. In the blade template.
                     <ul>
                      @foreach($Mytree as $node)
                        
                        
                        {!!renderNode($node)!!}
                        

                      @endforeach
                    </ul>   

And you are done:

Although i am surprised that {!!renderNode($node)!!} is equivalent to <?php echo renderNode($node); ?> in terms of blade templating.

And not {{renderNode($node)}} which will display the child together with the HTML as strings...Try and See

Hope this helps.

And my BAUM class declaration:

<?php

namespace App;

use Baum\Node;

/**
* MyTree
*/




class Mytree  extends Node {

  /**
   * Table name.
   *
   * @var string
   */
  protected $table = 'Mytrees';
}
3 likes

Please or to participate in this conversation.