[英]if and else condition not working in laravel for the array of data
其他情況,對不起,當購物車為空時,您的購物車中沒有商品無法打印
@if($datas)
@foreach($datas as $data)
<h5>This is product</h5>
@endforeach
@else
<h5>Sorry no items in your cart</h5> // Not printing when cart is empty
@endif
這可能是您將$datas
作為一個空集合。
如果您從 Eloquent 模型中獲取$datas
isNotEmpty
的集合,那么您可以使用isNotEmpty
進行檢查,如下所示
@if($datas->isNotEmpty())
@foreach($datas as $data)
<h5>This is product</h5>
@endforeach
@else
// $data is empty
@endif
有關更多信息,請參閱文檔
或者您可以簡單地通過empty()
(對於數組)方法進行檢查,如下所示
@if(!empty($datas))
@foreach($datas as $data)
<h5>This is product</h5>
@endforeach
@else
// $data is empty
@endif
如果它的數組數據則使用empty()
@if(!empty($datas))
@else
@endif
或其他方式使用count()
@if(count($datas) > 0)
@else
@endif
或者如果它的集合然后使用isEmpty()
@if(!$datas->isEmpty())
@else
@endif
使用 empty() 函數檢查數組是否為空
@if(!empty($datas))
@foreach($datas as $data)
<h5>This is product</h5>
@endforeach
@else
//do
@endif
我幾乎可以看到答案。 但是讓我解釋一下。我可以看到您正在檢查$datas
是否為空。 如果您使用輔助函數dd()
轉儲$datas
值,您可以看到它總是從Illuminate\\Support\\Collection
返回一個Illuminate\\Support\\Collection
。 所以即使$datas
是空的,它也會給出一個空的集合。 你可以像下面這樣在你的控制器中自己測試這個
if($datas) {
dd($datas);
}else{
dd('empty');
}
這將始終顯示空集合。 因此,僅使用if
條件您無法檢查集合是否為空。 相反的if
你可以檢查一個集合下面的方法。
collect([])->isEmpty();
@if ($datas->isEmpty()) @endif
collect([])->isNotEmpty();
@if ($datas->isNotEmpty()) @endif
collect([])->first();
@if ($datas->first()) @endif
collect([])->count();
@if ($datas->count()) @endif
如果您查看 Laravel Collection 文檔,您可以找到更多信息。
編輯 01這個答案直接回答你的問題。 請檢查
您可以使用 laravel 的 forelse 循環 - https://laravel.com/docs/6.x/blade#loops
@forelse ($datas as $data)
<h5>This is product</h5>
@empty
<h5>Sorry no items in your cart</h5>
@endforelse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.