如何检查 Laravel 集合是否为空?
How to check if a Laravel Collection is empty?
我通过执行 eloquent 查询创建视图,然后将其传递给 Blade。
@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif
然而,它总是假设 $contacts 有一些东西,即使查询什么也没给我。
我做了 dd($contacts)
并得到:
Collection {#247 ▼
#items: []
}
如何检查是否为空?
如果它是一个 Eloquent 集合,因为它看起来来自您的示例,您可以使用 isEmpty 集合辅助函数;
@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif
您的 Eloquent 查询 returns 结果数组,因此您可以使用 count
.
@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
您的 $contacts
是空的。 Bcoz 您的查询无法获取数据。一旦您的查询无法获取数据,它就是 return 一个空的 arrya。所以检查一下
@if($contacts->isEmpty())
{{ 'Empty' }}
@else
{{ 'you have data' }}
@endif
有几种方法:
if (!empty($contacts))
if (!contacts->isEmpty())
if (count($contacts) > 0)
if ($contacts->count() > 0)
您可以使用 blank($contacts)
助手 Laravel:blank
if(count($profiles) > 0){
return redirect()->action('NameController@name');
}else{
return view('user');
}
这在控制器中也能正常工作
您必须执行以下操作:
在您的“ContactController”视图中:
public function index()
{
$contacts = Contact::all();
return view('page.index', compact('contacts'))
}
稍后查看“index.blade.php”:
@if (collect($contacts)->isEmpty()) {{-- remember that $contact is your variable --}}
<p>There is no record available at this time</p>
@else
@foreach($contacts as $contact)
{{$contact->name_contact}}
@endforeach
@endif
现在,我想你有一个名为 Contact
的模型
我在我的助手中添加了全局方法 class
function isNullOrEmpty($value)
{
return is_null($value) || empty($value);
}
我通过执行 eloquent 查询创建视图,然后将其传递给 Blade。
@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif
然而,它总是假设 $contacts 有一些东西,即使查询什么也没给我。
我做了 dd($contacts)
并得到:
Collection {#247 ▼
#items: []
}
如何检查是否为空?
如果它是一个 Eloquent 集合,因为它看起来来自您的示例,您可以使用 isEmpty 集合辅助函数;
@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif
您的 Eloquent 查询 returns 结果数组,因此您可以使用 count
.
@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
您的 $contacts
是空的。 Bcoz 您的查询无法获取数据。一旦您的查询无法获取数据,它就是 return 一个空的 arrya。所以检查一下
@if($contacts->isEmpty())
{{ 'Empty' }}
@else
{{ 'you have data' }}
@endif
有几种方法:
if (!empty($contacts))
if (!contacts->isEmpty())
if (count($contacts) > 0)
if ($contacts->count() > 0)
您可以使用 blank($contacts)
助手 Laravel:blank
if(count($profiles) > 0){
return redirect()->action('NameController@name');
}else{
return view('user');
}
这在控制器中也能正常工作
您必须执行以下操作:
在您的“ContactController”视图中:
public function index()
{
$contacts = Contact::all();
return view('page.index', compact('contacts'))
}
稍后查看“index.blade.php”:
@if (collect($contacts)->isEmpty()) {{-- remember that $contact is your variable --}}
<p>There is no record available at this time</p>
@else
@foreach($contacts as $contact)
{{$contact->name_contact}}
@endforeach
@endif
现在,我想你有一个名为 Contact
的模型我在我的助手中添加了全局方法 class
function isNullOrEmpty($value)
{
return is_null($value) || empty($value);
}