Posted: 22-08-2019

Eloquent: Create one query recursive tree with Laravel Collection

Eloquent: Create one query  recursive tree with Laravel Collection

How to create a simple recursive tree with Eloquent and Laravel Collection

This article has been inspired by the excellent post  Eloquent: Recursive hasMany Relationship with Unlimited Subcategories published on laraveldaily.com.

In this article, the author Povilas Korop, shares a "trick" that use  Recursive hasMany Relationship to create an unlimited subcategories tree menu.

Run the code on my local env has have seen that a lot of queries have been done to create the tree.

So I tried to reproduce the same result using just one query and the Laravel collection where filter.

In my example I've used parent_id field as foreign key to refer any children to his parent.

First of all in my controller have done this simple query that retreive all items in the Articles table.

function index()
{
$articles = Article::orderBy('sort')->get();// get all the article items
return view('/tree', compact('articles'));
}

 
Then create a view resources/views/tree.blade.php:
and a child component resources/views/child_tree.blade.php

Then run the code and inspect your Debugbar


Same result but only with one query. The trick is using the Laravel collection where filter

$articles->where('parent_id', $child_article->id)