if和else条件在laravel中不适用于数据数组

时间:2020-02-06 04:33:55

标签: php laravel laravel-blade

其他情况,很抱歉,购物车为空时,购物车中没有任何项目无法打印

@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

5 个答案:

答案 0 :(得分:2)

这可能是您将$datas作为空集合。

如果您从Eloquent模型中的$datas中获取了一个集合,则可以使用isNotEmpty进行检查,如下所示

@if($datas->isNotEmpty())
    @foreach($datas as $data)
        <h5>This is product</h5>
    @endforeach
@else
    // $data is empty
@endif

有关更多信息,请参见documentation

或者您可以通过下面的empty() (用于数组)方法进行检查

@if(!empty($datas))
    @foreach($datas as $data)
        <h5>This is product</h5>
    @endforeach
@else
    // $data is empty
@endif

答案 1 :(得分:1)

如果其数组数据,则使用 empty()

@if(!empty($datas))
@else
@endif

或其他方式使用 count()

@if(count($datas) > 0)
@else
@endif

,或者如果其集合,则使用 isEmpty()

@if(!$datas->isEmpty())
@else
@endif

答案 2 :(得分:1)

使用empty()函数检查数组是否为空

public class SampleConfigurations : IEntityTypeConfiguration<Sample>
{
    public void Configure(EntityTypeBuilder<Sample> builder)
    {
        builder.Ignore(item => item.columnproperty);
    }
}

答案 3 :(得分:0)

我几乎可以看到答案。但是,请允许我解释更多。我可以看到您正在检查$datas是否为空。如果您使用辅助函数dd()来转储$datas的值,您会看到它总是从Illuminate\Support\Collection返回一个Collection。因此,即使$datas为空,它也会提供一个空Collection。您可以像下面在控制器中那样自行进行测试

if($datas) {
   dd($datas);
}else{
   dd('empty');
}

这将始终显示空的收藏集。因此,仅使用if条件就无法检查集合为空。您可以使用以下方法来检查集合,而不是if

  1. collect([])->isEmpty();

    @if ($datas->isEmpty())
    
    @endif
    
  2. collect([])->isNotEmpty();

    @if ($datas->isNotEmpty())
    
    @endif
    
  3. collect([])->first();

    @if ($datas->first())
    
    @endif
    
  4. collect([])->count();

    @if ($datas->count())
    
    @endif
    

如果您查看Laravel Collection文档,则可以找到更多信息。

Collections full documentation

Location above methods available

编辑01 此答案直接回答您的问题。请检查

Eloquent Collection: Counting and Detect Empty

答案 4 :(得分:0)

您可以使用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