Forelse Without Empty #41477
-
I have been switching most of my code over to using I realized that the There are many times in which An example of this is that you want to verify that a collection is not empty but if it is empty, there is nothing displayed. Using the The below example shows the current method versus the current method with {{-- current solution with @if & @foreach directives to ensure a collection is non empty before looping --}}
@if(!$collection->isEmpty())
@foreach($collection as $collect)
{{-- do something --}}
@endforeach
@endif
{{-- current solution with @forelse directives to ensure a collection is non empty before looping --}}
@forelse($collection as $collect)
{{-- do something --}}
@empty
@endforelse
{{-- requested functionality with @forelse directives to ensure a collection is non empty before looping --}}
@forelse($collection as $collect)
{{-- do something --}}
@endforelse Let me know what you think, I could be misunderstanding the use of the Its quite possible that there is a better way too! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi there ✋🏻 . TLDR:
Kind of... The idea of the e.g. This displays a message when the @forelse ($posts as $post)
{{ $post->title }}
@empty
¡There are not posts!
@endforelse If you don't want to display any message when the when the @foreach ($posts as $post)
{{ $post->title }}
@endforeach |
Beta Was this translation helpful? Give feedback.
Hi there ✋🏻 .
TLDR:
Use
@forelse
if you want an elegant way to handle empty states using Blade.Use
@foreach
for regular loop statements.Kind of...
The idea of the
@foresle
is to add an elegant way to handle empty states using Blade.e.g. This displays a message when the
posts
collections is emptyIf you don't want to display any message when the when the
posts
collections is empty, you can use the regular@foreach
blade statement.e.g.