My laravel version is 5.4.36. I want to use forelse
to show message when the condition is not meet.
@forelse ($items as $item)
<p>
@if ($item->quantity<$item->minimum_no)
<span class="label label-danger">Item {{$item->name}} need to be ordered now ! </span>
@elseif($item->quantity<($item->minimum_no+10))
<span class="label label-warning">Item {{$item->name}} is low !</span>
@endif
</p>
@empty
<p>No message</p>
@endforelse
But, it only show the message when the condition is meet. When it is @empty
, it does not show anything.
@forelse
acts exactly like @foreach
with one diff which is @empty
command that will works if your array was empty
in the following example if $users
was empty then no users
will be place:
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
in your code if $item
is empty then <p>No message</p>
will be placed and if it has one or more item then if..else...
will works
UPDATE depend on your condition if your condition is about item but not items so you need additional variable for checking it at end or something like it:
<?php $elseMsg='<p>No message</p>';?>
@foreach ($items as $item)
<p>
@if ($item->quantity<$item->minimum_no)
<?php $elseMsg='';?>
<span class="label label-danger">Item {{$item->name}} need to be ordered now ! </span>
@elseif($item->quantity<($item->minimum_no+10))
<?php $elseMsg='';?>
<span class="label label-warning">Item {{$item->name}} is low !</span>
@endif
</p>
@endforelse
{{$elseMsg}}
You have a logical branch that will have no output here (besides the paragraph tags). If the array or collection, iterable, isn't empty and you don't meet the conditions of the if
or the elseif
in the foreach
then you have a path with no defined output.
If you add a else
to the if ... elseif ...
you should see output:
@if (...)
...
@elseif (...)
...
@else
<span class="label label-info">reached the else</span>
@endif
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.