N
N
Nubbb2020-06-14 17:42:06
Laravel
Nubbb, 2020-06-14 17:42:06

Outputting subcategories in Laravel?

how to get rid of so many queries when displaying subcategories Category

5ee636ef09462759857055.png

model

class Category extends Model
{
    protected $table = 'categories';

    protected $fillable = [
        'image','parent','sort_order','published'
    ];

    public function description()
    {
        return $this->hasOne(CategoryDescription::class);
    }
    
    public function childrens()
    {
        return $this->hasMany(Category::class, 'parent');
    }
}


I display categories for the menu like this

$categories = Category::where('parent','=',0)->with(['childrens','description' => function($query){
                $query->where('language_id', '=', Session::get('lnaguage_id));
            }])->get();

            $view->with([
                'categories' =>  $categories,
            ]);


view

@foreach($categories as $category)
                @if($category->childrens)
                    <div class="menu-sub divany-i-kresla" id="menu-{{$category->id}}" data-category="{{$category->slug}}">
                        <button class="btn-close btn-close_sub_menu">
                            <svg><use href="#close"></use></svg>
                        </button>
                        <div class="menu-sub_title">
                            <a href="/categories/{{$category->slug}}">{{$category->description->name}}</a>
                        </div>

                        <ul class="menu-sub_categories">
                            @foreach($category->childrens as $children)
                                <li>
                                    <a href="/categories/{{$category->slug}}/{{$children->slug}}">
                                        <img src="{{$children->image}}" alt="{{$children->description->name}}">
                                        <span>{{$children->description->name}}</span>
                                    </a>
                                </li>
                            @endforeach
                        </ul>
                    </div>
                @endif
            @endforeach

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nubbb, 2020-06-14
@Nubbb

I don’t know how true, but in the Category model I did this

public function childrens()
    {
        return $this->hasMany(Category::class, 'parent')->with('description');
    }

D
Dinesh_Chugtai, 2020-06-14
@Dinesh_Chugtai

Check out this package for how it's done. There is what you need: https://github.com/lazychaser/laravel-nestedset

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question