Reputation: 1886
I have a Model Category
and a Model Subcategory
. These are related.
Now I want to check in a view if a category has subcategories. If so, run this code, if not run this code.
I thought of something like
@forelse($categories as $category)
@if($category->subcategory)
<li class="sub-category">
<a href="#"><img src="{{ asset('img/icon/'.$category->icon) }}" alt="{{ $category->name }}">{{ $category->name }}</a>
<ul class="sub-menu clearfix">
@foreach(isset($category->subcategory)) as $subcategory)
<li class="sub-sec col-md-6">
<ul>
<li><a href="#" class="title">{{ $subcategory->name }}</a></li>
<!--//
<li><a href="#"><i class="fa fa-angle-double-right"></i> Single Item 1</a></li>
<li><a href="#"><i class="fa fa-angle-double-right"></i> Single Item 2</a></li>
<li><a href="#"><i class="fa fa-angle-double-right"></i> Single Item 3</a></li>
<li><a href="#"><i class="fa fa-angle-double-right"></i> Single Item 4</a></li>
-->
</ul>
</li>
@endforeach
</ul>
</li>
@else
<li><a href="#"><img src="{{ asset('img/icon/'.$category->icon) }}" alt="{{ $category->name }}">{{ $category->name }}</a></li>
@endif
@empty
@endforelse
But using isset()
seems to be wrong
Upvotes: 0
Views: 394
Reputation: 3226
There is a simple way to do this. Just use the count of subcategories to determine.
Example:
if ($category->subcategory()->count() > 0)
Maybe you should also change some names of variables, methods and relations. It makes reading much easier. For example you could rename your subcategory relations to subcategories since it will be more than one.
Your code would look something like:
@forelse ($categories as $category)
<li>
<a href="...">{{ $category->name }}</a>
@if ($category->subcategory()->count() > 0) // Check if more than one subcategory
@foreach($category->subcategories as $subcategory) // Change $category->subcategory to $category->subcategories
...
@endforeach
@endif
</li>
@empty
No categories
@endforelse
Hope this helps :)
Upvotes: 1