检查集合是否存在

Check collection exist

我有这个代码:

@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

上面的代码有时会出错:

Trying to get property 'id' of non-object (View: /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 函数不显示错误?

您可以检查 $subCategories 变量的计数是否大于 0

@if($subCategories->count())
here goes your loop
@endif

laravel 集合实例有一个名为 count 的方法。您可以用它来检查集合的长度,并仅在它至少有 1 个结果时才对其进行循环。

if $subCategories->count() returns 0 它将解释为 FALSE 并且不会输入下面的代码。一旦 $subCategories->count() 大于 0,它就会为真并执行 if 语句中的代码。如果您需要更多解释,请随时询问。