【发布时间】:2020-05-26 14:01:32
【问题描述】:
我有这个代码:
@foreach($subCategories as $subCategory)
<tr data-id="{{ $subCategory->id }}" id="{{ $subCategory->id }}" class="sortItem">
<td class="text-left">
{!! Str::limit($subCategory->category_name, 80, '...') !!}
<p class="text-muted"></p>
</td>
<td class="text-center">
@if ($subCategory->enable == 1)
<span class="label font-weight-bold label-lg label-light-success label-inline">
<i class="ft-thumbs-up"></i> aktywny
</span>
@else
<span class="label font-weight-bold label-lg label-light-danger label-inline">
<i class="ft-thumbs-down"></i> nieaktywny
</span>
@endif
</td>
<td class="text-center">
<a href="{{ route('subcategory.index', ['parentId'=>$subCategory->id]) }}" class="badge badge-primary badge-md h-30px">
<i class="ft-aperture"></i> Rozwiń
</a>
<a href="{{ route('subcategory.edit', ['id'=>$subCategory->id]) }}" class="badge badge-info badge-md h-30px">
<i class="ft-aperture"></i> Edytuj
</a>
<form method="post" action="{{ route('subcategory.destroy', ['id'=>$subCategory->id, 'parentId'=>$parentId]) }}" class="d-inline-block" onSubmit="showAlert();{return false;}">
@method('DELETE')
{{ csrf_field() }}
<input type="submit" class="removeBtn" value="Usuń">
</form>
</td>
</tr>
@endforeach
上面的代码有时候会出错:
试图获取非对象的属性“id”(查看: /var/www/resources/views/admin/categories/subcategory_list.blade.php)
当我调试时,问题是在我的 $subCategory 中有:
App\Models\Category {#487 ▼
#quarded: array:1 [▶]
#fillable: array:11 [▶]
+timestamps: false
#connection: "mysql"
#table: "categories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▶]
#original: array:12 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
#pending: null
#moved: false
}
当我在调试时:
Kalnoy\Nestedset\Collection {#487 ▼
#items: array:3 [▼
0 => App\Models\Category {#1423 ▶}
1 => App\Models\Category {#1422 ▶}
2 => App\Models\Category {#1426 ▶}
]
}
这段代码运行良好。
如何确保我的 foreach 函数不显示错误?
【问题讨论】:
-
我猜最简单的就是查id
@if (isset($model->id)) -
请分享更多细节。通常,循环不应返回
NULL的元素 -
哪一行抛出该错误?
$subCategory->id调用都不会导致该错误。如果每个$subCategory都是Category模型的一个实例,那么它就是一个对象,->id将返回id或null。您看到此错误的主要时间是尝试访问array(['id']) 或null(->id和['id']都会失败)上的属性(如->id)时
标签: php laravel laravel-5 laravel-7