mercredi 4 octobre 2017

Don't show empty parent category in Laravel

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire