Laravel 4 - Eloquent. Infinite children into usable array?

I've got a categories table. Each category can have an optional parent (Defaults to 0 if no parent).

What I want to do is build a simple html list tree with the levels of the categories.

Example date:

-- Fruit
---- Apple
---- Banana
---- Orange
-- Veg
---- Cucumber
---- Lettuce
-- Alcoholic
---- Beer
---- Vodka
-- Household Objects
---- Kitchen
------ Electrical
-------- Cooking
---------- Stove
---------- Toaster
---------- Microwave

Note that this needs to work for around 10 'levels'. I'd love it to be infinite but I really dont want to be going down the route of using a nested set model as it'll cause huge delays on this project.

The docs on this for laravel are terrible, with no real reference as to where to even start. I've been playing with it for days trying to work out what to do and seem to be getting nowhere without a huge messy block of for each loops within each other 10 times.

I've got my tree of data using the following in my model:

class Item extends Eloquent {
    public function parent()
        return $this->hasOne('Item', 'id', 'parent_id');

    public function children()
        return $this->hasMany('Item', 'parent_id', 'id');

    public function tree()
        return static::with(implode('.', array_fill(0,10, 'children')))->where('parent_id', '=', '0')->get();

This gets all the parent and children up to a level of 10. This works fine, but you cant really then do anything with the child data without manually having 10 foreach loops within each other.

What am I doing wrong here? Surely this shouldn't be this hard/poorly executed? All I want do do is get a simple html list with the items in a tree structure.

I've put together a quick SQLFiddle example of the dummy data used above:!2/e6d18/1


This was much more fun than my usual morning crossword puzzle. :)

Here is an ItemsHelper class that will do what you are looking for, and better yet will recurse as far down as you want.



  class ItemsHelper {

    private $items;

    public function __construct($items) {
      $this->items = $items;

    public function htmlList() {
      return $this->htmlFromArray($this->itemArray());

    private function itemArray() {
      $result = array();
      foreach($this->items as $item) {
        if ($item->parent_id == 0) {
          $result[$item->name] = $this->itemWithChildren($item);
      return $result;

    private function childrenOf($item) {
      $result = array();
      foreach($this->items as $i) {
        if ($i->parent_id == $item->id) {
          $result[] = $i;
      return $result;

    private function itemWithChildren($item) {
      $result = array();
      $children = $this->childrenOf($item);
      foreach ($children as $child) {
        $result[$child->name] = $this->itemWithChildren($child);
      return $result;

    private function htmlFromArray($array) {
      $html = '';
      foreach($array as $k=>$v) {
        $html .= "<ul>";
        $html .= "<li>".$k."</li>";
        if(count($v) > 0) {
          $html .= $this->htmlFromArray($v);
        $html .= "</ul>";
      return $html;

I just used a new installation of Laravel 4 and the basic hello.php view.

Here is my route in app/routes.php:

Route::get('/', function()
  $items = Item::all();
  $itemsHelper = new ItemsHelper($items);
  return View::make('hello',compact('items','itemsHelper'));

Although my view doesn't use the items variable, I'm passing it here because you probably will want to do something else with them too.

And finally, my app/views/hello.php just has one line:

<?= $itemsHelper->htmlList(); ?>

The output looks like this:

  • Foods
    • Fruit
      • Apple
      • Banana
      • Orange
    • Veg
      • Cucumber
      • Lettuce
  • Drinks
    • Alcoholic
      • Beer
      • Vodka
  • Misc
    • Household Objects
      • Kitchen
        • Electrical
          • Cooking
            • Stove
            • Toaster
            • Microwave

Note: your SQL Fiddle had 5 ("Orange") as the parent_id for Cucumber and Lettuce, I had to change it to 6 ("Veg").

I use this functions to make it work.

 //Returns Root elements
 public function scopeRoot($query) {
        $all = $query->whereParent(0)->get();
        $collection = $all->filter(function($single) {
            if ($single->ModelFilter('GET')) {
                return $single;
        return $collection;
    //Recursive call
    public function traverse() {
        self::_traverse($this->Children, $array, $this);
        return $array;

    //This function build a multidimensional array based on a collection of elements
    private static function _traverse($collection, &$array, $object) {
        $new_array = array();
        foreach ($collection as $element) {
            self::_traverse($element->Children, $new_array, $element);
        $array[] = $object;
        if (count($new_array) > 0) {
            $array[] = $new_array;

First I get a collection of the root elements those are the ones that I pass to my views where I want to list the tree...

Then I do ...

 <ul class="bg-info cat-list">
        @foreach($categories as $category)
        $array = $category->traverse();

Using this function...

//Prints a multidimensional array as a nested HTML list
function list_view($element, $ul = true) {
    foreach ($element as $value) {
        if (!is_array($value)) {
            echo "<li>";
            echo $value->name;
        } else {
            echo ($ul) ? "<ul>" : "<ol>";
            list_view($valuce, $ul);
            echo "</li>";
            echo ($ul) ? "</ul>" : "</ol>";

Hope it helps

I've expanded on the accepted answer by Mark Smith to allow generated lists to reference addition data that is passed into the class.

The class works in pretty much the same way, but I've packaged it up so hopefully it can be used easily.

Just reference the helper class in your controller:

use App\Helpers\CategoryHierarchy;

You can then either instantiate the class manually, or using Laravel 5's method injection things get even better:

$products = $product->getAllProducts();
return $hierarchy->render();

This can output the following:

<ul class='simple-list'>
   <li><input type="checkbox" name="hierarchy-checkboxes[]" value="1" >Home delivery</li>
        <li><input type="checkbox" name="hierarchy-checkboxes[]" value="2" >Italian</li>
            <li><input type="checkbox" name="hierarchy-checkboxes[]" value="3" >Pizza</li>
            <li><input type="checkbox" name="hierarchy-checkboxes[]" value="4" >Pasta</li>
        <li><input type="checkbox" name="hierarchy-checkboxes[]" value="5" >Burgers</li>

A repo is available: which explains in some more detail.

Need Your Help

activity stops unexpactedly when using Intent

android android-intent fatal-error

hello stackoverflowers i m new bee to the android. could any one help me out to run away from FATAL Error as followed.

In ZK Can we PostNotifyChange more than one variables

java zk notify

I will want to notify some specific variables of a class with the help of

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.