简体   繁体   中英

Detect 'false' with laravel @forelse and stop looping

I have a loop which sometimes has no data. I'm trying to prevent the looping of data if the array item is empty/false etc.

@forelse($section['menu_items'] as $menu_item)

    MENU ITEMS

@empty

  {{-- No menu items available --}}

@endforelse

The value of $section['menu_items'] is:
/tmp/sage-cache/2acaf3eba50e1836f9f0ccc295cb9d19c73d0fec.php:105:boolean false

Based on this error, it's still trying to loop but also falls back to the @else result too:

在此处输入图片说明

Why don't you just check it before you try to loop through it?

@if(!empty($section['menu_items']))
    @foreach($section['menu_items'] as $menu_item)
        MENU ITEMS
    @endforeach
@else
    {{ -- No menu items available --}}
@endif

Try this

@forelse($status->replies as $reply)

        <p>{{ $reply->body }}</p>

    @empty

       <p>No replies</p>

 @endforelse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM