How can I hide a block in Laravel?

Viewed 95

There is one div inside which foreach works for me. Before this div I do a check

@if($events)
 <div class="card mb-5">
 ....

If true, then show the block, if false, do not show. But the block is still visible, it returns me an empty collection. How to fix it?

public function index($id) {
    $user = User::find($id);
    $events = $user->events()->orderBy('eventdata', 'desc')->limit(3)->get();
3 Answers

Because you are using get() method it always returns Collection of items but sometimes empty. I think you are checking whether $events collection is empty or not. So, you have to use $events->count() inside if

@if($events->count())
 <div class="card mb-5">
 ....
@forelse($events as $event)
 <div class="card mb-5">
 ....
@empty
 Do something if there is no event
 ...
@endforelse

@forelse checks if $events variable empty or not. If it is empty then @empty block will be rendered else @forelse block will be rendered. @forelse is like a combination of @foreach @if and @else directives

You try this

@if(count($events)>0)
    <div class="card mb-5">
Related