LonnieD
1 month ago

Recursive Eloquent using "with" Method?

Posted 1 month ago by LonnieD

I'm building an application that uses animal taxonomy data using the adjacency list method of representing the hierarchy in a MySQL database.


id | name | parent_id
---------------------------------
1 | Family | null
2 | Subfamily_1| 1
3 | Subfamily_2 | 1
4 | Genus_1 | 2
5 | Genus_2 | 3

After reading through several tutorials on getting the parent and children of an Eloquent model using adjacency list, I am able to get a single parent and the immediate children of a model using the following.


app\Taxon.php;

// Returns the parent of a taxon
public function parent()
{
        return $this->belongsTo('App\Taxon', 'parent_id', 'id');
}

// Returns all of the immediate children of a taxon
public function children()
{
        return $this->hasMany('App\Taxon', 'parent_id', 'id');
}

Then after further research in getting all parents and children of a given model recursively, I came across a technique using the "with" method for Eloquent Relationships to do this.


app\Taxon.php

// Returns all parents of a Taxon model
public function allParents()
{
     return $this->parent()->with('allParents');
}

The above method, allParents() returns something interesting I can't make sense of and need help understanding so I can send a list of "parents" to a view.

The above "allParents()" method returns an Eloquent collection with all properties of the immediate parent Taxon along with an additional property called "allParents" which itself is an Eloquent collection containing Taxon properties and so on until there are no more "parents" for my chosen Taxon. So the allParents() method works just fine in returning all of the "parents", but I don't know how to send the whole collection to a view to list out all of the parents.

This is a sample of what is returned from php artisan tinker


>>> $parents = $taxon->allParents;
=> App\Taxon {#3038
     id: 53,
     name: "Acanthopelma",
     parent_id: 5,
     allParents: App\Taxon {#3030
       id: 5,
       name: "Ischnocolinae",
       parent_id: 1,
       allParents: App\Taxon {#3024
         id: 1,
         name: "Theraphosidae",
         parent_id: null,
         allParents: null,
       },
     },
   }

How do I return a collection or array to a view given this kind of output so that I can display the entire hierarchy as a list such as the one below. You will notice that the list below contains only the name property from the collection above, but in reverse order.

  • Theraphosidae
  • Ischnocolinae
  • Acanthopelma

Please sign in or create an account to participate in this conversation.