PereraSH
PereraSH

Reputation: 199

How to retrive data from database to a treeview using laravel

My requirement is to construct the treeview using database values.

Here are my database tables:

|    Categories   |  |sub_categories   |
|     id(pk)      |  |    id(pk)       |
|  cate_name      |  | sub_cat_name    |
| route_name      |  | route_name      |
                     |Categories_id(fk)|

I'm getting categories and sub categories as well which are related to categories table.

Here is my Controller code:

$treeView = DB::table('categories')
                ->join('sub_categories', 'sub_categories.categories_id', '=', 'categories.id')
                ->get();

Here is the HTML structure in the *.blade.php :

@foreach($treeView as $tv)
                <li class="treeview">
                    <a href="#"><i class="fa fa-link"></i> <span>{{ $tv->category_name }}</span> <i
                                class="fa fa-angle-left pull-right"></i></a>
                    <ul class="treeview-menu">
                        <li class=""><a href="#">{{$tv->sub_category_name}}</a></li>
                        <li><a href="#">Update Article</a></li>
                    </ul>
                </li>
            @endforeach

But it doesn't work fine. It gives same main category again and again.. Can anyone suggest a proper way to retrieve data?

Upvotes: 0

Views: 3630

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

I suggest you use Eloquent, as it will make the code simpler and will make your life easier in the future.

Create model classes for your tables:

class Category extends Illuminate\Database\Eloquent\Model {
  protected $table = 'Categories';

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

class Subcategory extends Illuminate\Database\Eloquent\Model {
  protected $table = 'sub_categories';

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

In your controller fetch data like that:

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

And then in the view:

@foreach($treeView as $category)
  <li class="treeview">
    <a href="#"><i class="fa fa-link"></i> <span>{{ $category->cate_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>
@endforeach

I can see that your categories and subcategories have the same stucture. You might consider storing them in the same table, just add a parent_id field to the table and set it to NULL for parent categories and to parent id for subcategories.

Upvotes: 4

Related Questions