Eloquent Parent-Child relationship on same model

Eloquent Parent-Child relationship on same model

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Recursive Eloquent Relationships: Handling Same-Model Hierarchies

When defining a self-referential relationship in Laravel, such as a CourseModule that acts as both parent and child within the same table, the initial setup often feels straightforward. You define a belongsTo pointing to itself via a parent_id column and a corresponding hasMany where the foreign key exists.

However, the moment you attempt to serialize this data into a JSON structure representing a deep tree—where children are nested inside parents, which are nested inside their own children—the standard eager loading approach hits a wall. The code snippet below only retrieves the immediate children:

$modules = CourseModule::with('children')->get();

This query fetches the root nodes and loads their first-level descendants. It does not recursively load grandchildren, great-grandchildren, or any deeper levels. Consequently, when you iterate over the collection to build your JSON output, the nested arrays stop at depth one, leaving the rest of the hierarchy empty.

To achieve the expected deep nesting shown in your target JSON output, you cannot rely on a single ->with() call because Eloquent's eager loading is non-recursive by design. Instead, you must implement a recursive traversal function that manually loads children as it descends the tree.

Implementing Recursive Traversal

The most robust way to handle this without writing custom SQL or using complex query scopes is to define a method on your model that accepts an ID and returns a fully populated nested array. This approach keeps the logic encapsulated within the model class.

First, ensure you are eager loading the immediate children in your initial query:

$rootModules = CourseModule::with(['children' => function ($query) {
    $query->where('parent_id', 0); // Only load direct children of roots if needed
}])->get();

Then, create a helper method within CourseModule to handle the recursion:

public static function getNestedTree($parentId = null)
{
    // Fetch the immediate children based on the current parent ID
    $children = CourseModule::where('parent_id', $parentId ?? 0)->with(['children'])->get();

    return $children->map(function ($child) {
        $nestedChildren = static::getNestedTree($child->id);
        
        // Construct the array structure matching your expected output
        return [
            'id' => $child->id,
            'parent_id' => $child->parent_id,
            'course_id' => $child->course_id,
            'name' => $child->name,
            'description' => $child->description,
            'order_id' => $child->order_id,
            'created_at' => $child->created_at,
            'updated_at' => $child->updated_at,
            'children' => $nestedChildren,
        ];
    })->toArray();
}

How This Works

  1. Eager Loading at Each Level: By calling with(['children']) inside the loop (or rather, before mapping), we ensure that every time we descend a level, the next set of children is already loaded into memory. This prevents N+1 query problems within the recursive function.
  2. Base Case Handling: The recursion naturally terminates when there are no more rows in the database where parent_id matches the current node's ID. In that case, the query returns an empty collection, and the map operation yields an empty array for the children key.
  3. Serialization Control: Rather than relying on Eloquent's default $attributesToArray conversion which might include unwanted fields or formatting issues, we explicitly construct the array keys in the method. This gives you precise control over the JSON output format, ensuring timestamps and IDs match your specific requirements.

Trade-offs and Considerations

While this pattern is clean and readable, it does carry memory overhead proportional to the depth of the tree. If you have a module with thousands of children at every level, constructing the entire nested array in PHP before returning it can consume significant RAM. For extremely large datasets, you might need to consider streaming the output or processing the data chunk-by-chunk on the frontend.

Additionally, be mindful of circular references if your data isn't strictly hierarchical (e.g., a cycle where A is parent of B and B is parent of A). Since this relies on parent_id, cycles are usually prevented by the database constraint requiring a non-circular path to the root, but logic errors in the foreign key setup could cause infinite loops.

For most application structures, however, this recursive mapping approach provides the exact tree structure required for JSON APIs without needing third-party packages or complex SQL queries involving UNION ALL and CROSS JOIN.

Our network