I have parent and child categories on the page. What I'm trying to do is when there is no products and no sub-categories assigned in some parent category to not be shown on the page.
So I have this in Category model
public function item()
{
return $this->hasMany('Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
This in the controller
public function index()
{
$Category = new Category;
$allCategories = $Category->getCategories();
return view('frontend.home', compact('allCategories', 'unviewedMessagesCount'));
}
And this on the blade view
@foreach($allCategories as $category)
{!!$category->title!!} ({!! $category->itemCount!!})
<p class="card-text">
@foreach($category->subCategory as $subcategory)
{!!$subcategory->title!!} {!! $subcategory->itemCount !!}
@endforeach
</p>
<a href="{!!route('list',array($category->id))!!}" class="btn btn-primary">View Category</a>
@endforeach
This is sample of the records in category table there are column
id | title | parent
1 Main cat 0
2 Sub-Cat 1
3 Sub-Cat 2 1
4 Main cat 2 0
So each parent is 0 and each child(sub category) has the parent ID
item
table has also reference to category
table -> column category_id
I can't figured it out how to make the condition if no items and no childs to not show it on page.
$categoires = Category::has('children')->has('children.item')->where('parent_id',0)->get();
– MarabocSQLSTATE[42S22]: Column not found: 1054 Unknown column 'parent_id' in 'where clause'
– user7956165