I want to increase the depth int
each time children are in a item so I can pad out the a
tag.
Below is my code and I assumed this would work, however the number stays at 1 even though I have got children within my one of the items within $items
.
sidebar.blade.php
JavaScript
x
<nav class="flex flex-col mt-10">
<ul class="pl-4">
@foreach($items as $item)
<x-layouts.sidebar.items :item="$item"></x-layouts.sidebar.items>
@endforeach
</ul>
</nav>
sidebar.items.blade.php
JavaScript
<li>
@if(count($item) > 0)
<a href="{{ $item['href'] }}" class="focus:text-blue-500 dark-focus:text-blue-400 focus:outline-none w-full transition duration-500 ease-in-out pl-4 py-2 text-gray-700 dark:text-gray-400 hover:bg-blue-200 dark-hover:bg-blue-500 transition duration-500 ease-in-out block">
{{ $item['text'] }} {{ $depth }}
</a>
@if (count($item['children']) > 0)
<ul class="pl-4">
@foreach($item['children'] as $child)
<x-layouts.sidebar.items :item="$child" :depth="$loop->parent->index"></x-layouts.sidebar.items>
@endforeach
</ul>
@endif
@else
<hr>
@endif
</li>
SidebarItems.php
JavaScript
<?php
namespace AppViewComponentsLayoutsSidebar;
use IlluminateViewComponent;
use IlluminateViewView;
class Items extends Component
{
/**
* @var array
*/
public $item;
/**
* @var int
*/
public $depth;
/**
* Create a new component instance.
*
* @param array $item
* @param int $depth
*/
public function __construct($item = [], $depth = 1)
{
$this->item = $item;
$this->depth += $depth;
}
/**
* Get the view / contents that represent the component.
*
* @return View|string
*/
public function render()
{
return view('components.layouts.sidebar.items');
}
}
Data:
JavaScript
$this->items = [
[ 'href' => '/home', 'text' => 'Home', 'children' => [], 'active' => 'border-l-2 border-blue-500' ],
[ 'href' => 'javascript:void(0)', 'text' => 'Test', 'children' => [], 'active' => '' ],
[ 'href' => 'javascript:void(0)', 'text' => 'Websites', 'children' => [], 'active' => '' ],
[ 'href' => 'javascript:void(0)', 'text' => 'Websites', 'children' => [], 'active' => '' ],
[],
[
'href' => '/administration',
'text' => 'Administration',
'children' => [
[
'href' => 'javascript:void(0)',
'text' => 'Locked Devsites',
'active' => '',
'children' => []
]
],
'active' => ''
],
[ 'href' => 'javascript:void(0)', 'text' => 'Documentation', 'children' => [], 'active' => '' ],
[ 'href' => 'javascript:void(0)', 'text' => 'Logout', 'children' => [], 'active' => '' ]
];
Result:
JavaScript
Home 1
Test 1
Websites 1
Websites 1
Administration 1
Locked Devsites 5
Documentation 1
Logout 1
Advertisement
Answer
If I get it right what you want to achieve, you don’t even need the $depth
property, since the blade’s @foreach
directive has its own depth property which tells you how nested you are.
In your code, instead using:
JavaScript
:depth="$depth"
use:
JavaScript
:depth="$loop->depth"