简体   繁体   中英

Laravel Display sub categories

So i got a problem where i set up everything and tested the relationships but can't really wrap my head around how would i output the navigation correctly with nested categories this is my category model

public function products() {
    return $this->belongsToMany(Product::class);
}

public function parent()
{
    return $this->belongsTo(Category::class, 'parent_id');
}

public function children()
{
    return $this->hasMany(Category::class, 'parent_id');
}


public function getRouteKeyName()
{
    return 'slug';
}

which works, i tested with tinker and it gets children and parents correctly so how would one go about displaying it, this is the partial which i'm using for displaying categories and then i tried to call itself within the view, sort of like recursion, with now children, but it gets stuck on request and page won't load so i'm assuming it doesn't work like this

@if(count($categories))
<ul class="list-group">
    @foreach($categories as $category)
        <li class="list-group-item"><a href="/{{ $category->slug }}">{{ $category->name }}</a></li>
        @include('layouts.categories', ['categories' => $category->children])
    @endforeach
</ul>@endif

and this is method where i'm fetching categories, i did it this way so it can be avialable to all views, but i'm assuming this query is one that can be moddified

   View::composer('*', function ($view) {
        $view->with('categories', Category::all());
    });

my desired result is this

Men
 -Men's Shoes
Women
 -Women's Shoes

If you have too many categories you'll end up with a N+1 issue.

Add this to your model:

public function allChildren()
{
    return $this->children()->with('allChildren');
}

And then your composer should be:

   View::composer('*', function ($view) {
        $view->with('categories', Category::with('allChildren')->all());
    });

If you are crashing due to multiple queries, this may solve the issue for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM