Display tree structure in laravel blade

Viewed 654

i am trying to display tree structure in blade, and i need i little help.

So Here is my algorithm

public function fetchData($entry_id)
    {
        $results = TreeEntry::where('parent_entry_id', $entry_id)->get();

        $treeEntryList = [];
        
        foreach ($results as $result) {

            $data = [
                'id' => $result->entry_id,
                'parent_entry_id' => $result->parent_entry_id,
                'children' => $this->fetchData($result->entry_id)
            ];

            $treeEntryList[] = $data;
        }

And getting this kind of tree array array treee

And trying something like this, but only first child node getting displayed, and i want to show all elements. Any idea how to solve this? Recursion here, or maybe something else?

@extends('layouts.master')
@section('content')
    {{dd($resultList)}}
<div class="container">
    <br id="lang-container">
        @foreach ($resultList as $result)
            <div>{{$result['id']}}</div></br>
            @foreach ($result['children'] as $child)
                <div>{{$child['id']}}</div></br>
            @endforeach
       
        @endforeach
    </div>

@endsection
@section('js')
@endsection
1 Answers

Idea in my mind, is to use components, but didn't really used them yet, so, not sure if this work or not. First of all, run php artisan make:component TreeEntryListing, to create the component. Then, go to the created component, and insert this piece of code (Fix it if there is any problem with it)

@foreach ($children as $child)
   <div>{{$child['id']}}</div></br>
   @if(isset($children['children']))
     <x-tree-entry-listing children={{$children}}/> // If it had syntax error, use " for children
   @endif
@endforeach

Then, go to TreeEntryListing file and add $children to its constructor:


<?php

namespace App\View\Components;

use Illuminate\View\Component;

class TreeEntryListing extends Component
{
    public $children;

    /**
     * Create a new component instance.
     *
     * @param $children
     */
    public function __construct($children)
    {
        $this->children = $children;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.tree-entry-listing');
    }
}

And then, use this for the primary view:

...
@foreach ($resultList as $result)
            <div>{{$result['id']}}</div></br>
            <x-tree-entry-listing children={{$result['children']}} />
       
@endforeach
...

Hope it work!

Related