アリ・ナディム
アリ・ナディム

Reputation: 610

How to iterate nested data in laravel blade view?

I have below the draft implementation. The spec is to show the parent information and children-grandchildren information.

@foreach ($parent as $children)
    <x-icons.chevron-right>
    <h1>{{ $parent->name }}</h1>
    
    @if($person->has('children'))
        // go back at the top for nested for each
    @endif
@endforeach

One solution that you may recommend is to create an iterative function. But my problem for that, it does not completely render my component-icon chevron-right.

@php
function showHTML($person) {
    $html = '';
    foreach($person as $children) {
        $html .= `
            <x-icons.chevron-right>
            <h1>$person->name</h1>
        `;
        
        if ($person->has('children')) {
            $html .= showHTML($person->children);
        }
    }
    return $html;
}
@endphp

{!! showHTML($person) !!}

Just wondering if you guys have other solution for this to show nested with a component icon? I would appreciate any answer.

Upvotes: 0

Views: 254

Answers (2)

tempra
tempra

Reputation: 2331

Simply re-iterate the component if it has a children. In this case, the icon will be rendered properly.

So my usage would like this below:

<x-parent person="$person"></x-parent>

And my root component parent.blade.php. So If there is person has children I just re-iterate the component and pass his children as a prop:

@props(['person'])

<x-icons.chevron-right>
<h1>{{ $person->name }}</h1>

@if($person->has('children'))
  <x-parent person="$person->children"></x-parent>
@endif

Upvotes: 0

Irvan Rifai
Irvan Rifai

Reputation: 81

You can try => value on your foreach, that will fetch data array value from backend. Or can you show your code on backend (controller), that can easy to help you

@foreach ($parent as $children => $value)
    <x-icons.chevron-right>
    <h1>{{ $parent->name }}</h1>
    <h3>{{ $value->data }}<h3>
@endforeach

Upvotes: 1

Related Questions