Utilizzando Laravel 5.1, sto cercando di creare un elenco di menu da una tabella di categorie MySQL. Il mio fornitore di servizi restituisce i dati, ma non capisco come creare le categorie figlio in un ciclo foreach. Quando eseguo il ciclo, viene restituita solo l'ultima riga della query figlio. Qualsiasi guida sarebbe apprezzata.Laravel restituisce figli di genitori nello stesso tavolo
categorie Tabella
id | cat_name | cat_parent_id
--- | --------------| -------------
1 | Parent Cat 1 | NULL
2 | Parent Cat 2 | NULL
3 | Child Cat 1 | 2
4 | Child Cat 2 | 2
5 | Parent Cat 3 | NULL
6 | Child Cat 3 | 5
Risultato desiderato
Parent Cat 1
Parent Cat 2
Child Cat 1
Child Cat 2
Parent Cat 3
Child Cat 3
viewComposerServiceProvider.php
public function boot()
{
$this->composeTopCategoryNavigation();
$this->composeSubCategoryNavigation();
}
private function composeTopCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('top_cats', Category::whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
private function composeSubCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('sub_cats', Category::whereNotNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
intestazione vista
<ul>
@foreach ($top_cats as $top_cat)
<?php $top_cat_slug = str_slug($top_cat->cat_name, "-"); ?>
<li>{{ $top_cat->cat_name }}
@foreach ($sub_cats as $sub_cat)
@if ($sub_cat->cat_parent_id === $top_cat->id)
<ul>
<li{{ $sub_cat->cat_name }}</li>
</ul>
@endif
@endforeach
</li>
@endforeach
</ul>