I have the following code that shows the output of a search for users, groups and posts :
<header><h1>Users results</h1></header>
@foreach ($users as $user)
@include('user.userblock')
@endforeach
<header><h1>Groups results</h1></header>
@foreach ($groups as $group)
@include('group.gruopblock')
@endforeach
<header><h1>Posts results</h1></header>
@foreach ($posts as $post)
@include('post.postblock')
@endforeach
How can I hide the <header>
if one of them doesn't have results ?
@if (count($users))
<header><h1>Users results</h1></header>
@foreach ($users as $user)
@include('user.userblock')
@endforeach
@endif
and so on...
Using eloquent @if
and @endif
with it s count()
function:
@if(count($users))
<header><h1>Users results</h1></header>
@foreach ($users as $user)
@include('user.userblock')
@endforeach
@endif
@if(count($groups))
<header><h1>Groups results</h1></header>
@foreach ($groups as $group)
@include('group.gruopblock')
@endforeach
@endif
@if(count($posts))
<header><h1>Posts results</h1></header>
@foreach ($posts as $post)
@include('post.postblock')
@endforeach
@endif
You've got several choices on how to do it thanks to the nature of the Laravel collection. But an if check conditional on either side will work fine:
if (empty($users)) { // Your header and foreach}
if ($users->first()) { // Your header and foreach}
if (!$users->isEmpty()) { // Your header and foreach}
if ($users->count()) { // Your header and foreach}