Laravel中如何判断数组或Eloquent Collection是否非空?
问题场景与报错
后端获取Person对象并加载家庭成员的代码:
$person = Person::where('id', $id)->first(); if($person) { $person->family_members = FamilyMemberController::FamilyMemberOf($person->id); } else { $person->family_members = []; }
视图中判断家庭成员非空的代码:
if(!empty(array_filter($person->family_members))) { // 业务逻辑代码 }
执行时抛出错误:
array_filter(): Argument #1 ($array) must be of type array, Illuminate\Database\Eloquent\Collection given
问题原因
FamilyMemberOf方法返回的是Laravel Eloquent Collection对象,但array_filter仅接受数组类型参数;同时后端赋值时又可能返回空数组,导致需要兼容两种类型的非空判断。
解决方案
方法1:统一转成Collection后判断(推荐)
用Laravel的collect()函数把数组或Collection统一转为Collection类型,再用自带的isEmpty()方法判断:
$familyMembers = collect($person->family_members); if (!$familyMembers->isEmpty()) { // 执行你的业务代码 }
collect()会自动处理数组和Collection,统一类型后逻辑更简洁。
方法2:分别处理数组和Collection
直接判断类型,针对不同类型用对应的非空判断方式:
if (is_array($person->family_members)) { if (!empty(array_filter($person->family_members))) { // 数组非空的业务逻辑 } } else { if (!$person->family_members->isEmpty()) { // Collection非空的业务逻辑 } }
方法3:后端统一返回Collection(最优雅)
修改后端赋值逻辑,把空数组改成空Collection,从根源上统一类型:
if($person) { $person->family_members = FamilyMemberController::FamilyMemberOf($person->id); } else { // 用空Collection替代空数组 $person->family_members = collect([]); }
之后视图里直接用Collection的方法判断即可:
if (!$person->family_members->isEmpty()) { // 业务逻辑代码 }
内容的提问来源于stack exchange,提问作者Mustafa Poya
相关产品推荐
相关产品推荐

