需要检查对象在laravel中是否为空

问题描述:

我通过进行雄辩的查询来创建视图,然后将其传递给Blade.

I create a view by doing an eloquent query and then pass it over to Blade.

@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif

但是,即使查询什么也没给我,它总是假设$ contacts有东西.

However it always assume that $contacts has something even if the query gives me nothing.

我做了dd($contacts)并得到:

Collection {#247 ▼
  #items: []
}

如何检查它是否为空?

如果它是一个Eloquent集合(似乎来自您的示例),则可以使用isEmpty集合帮助器函数;

If it is a Eloquent Collection as it appears to be from your example you can use the isEmpty collection helper function;

@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif

收藏文档