Support the ongoing development of Laravel.io →
Database Eloquent Blade

I'm retrieving data from two tables which are categories and subcategories.

categories cat_id contains inside the subcategories table as a foreign key.

here is my code form Category model:

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

    public function subcategories()
    {
        return $this->hasMany(Subcategory::class, 'categories_id');
    }
}

here is my code form SubCategory model:

class Subcategory extends Model
{
    protected $table = 'sub_categories';

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

This is how I retrieve data from my controller:

 $treeView = Category::with(['subcategories'])->get();

this is how my .blade.php part looks like:

@foreach($treeView as $category)
                @if($category->has('subcategories'))
                    <li class="treeview">
                        <a href="#"><i class="fa fa-link"></i> <span>{{ $category->category_name }}</span>
                            <i class="fa fa-angle-left pull-right"></i></a>
                        <ul class="treeview-menu">
                            @foreach($category->subcategories as $subcategory)

                                <li class=""><a href="#">{{$subcategory->sub_category_name}}</a></li>

                            @endforeach
                        </ul>
                    </li>
                @else
                    <li><a href="#"><i class="fa fa-link"></i> <span>{{ $category->category_name }}</span></a></li>
                @endif

            @endforeach

As above html structure I m going to construct a tree view if any category has sub categories else show the category without a tree view . But I get all the categories with or without subcategories inside a tree view.. Can anyone suggest a way please...

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.