Catto
Catto

Reputation: 526

How to skip null collection inside array when doing a foreach

I have an array of collection like this:

array:2 [▼
  0 => Illuminate\Support\Collection {#1401 ▼
    #items: []
    #escapeWhenCastingToString: false
  }
  1 => Illuminate\Support\Collection {#1405 ▼
    #items: array:4 [▼
      0 => {#1407 ▼
        +"id": "887923fe-1993-4e5b-8a99-699d66be129c"
        +"employee_id": "887923fe-1993-4e5b-8a99-699d66be129c"
        +"in_time": "2022-01-10 11:31:44"

There's a null #items: inside it. And whenever I'm trying to loop the data, I always got error property not exist. I know it because the first collection item in my array is null. But I don't know how to skip it.

I've tried to use isNotEmpty(), but still got the error

@foreach ($attendance as $data)
    @if ($data->isNotEmpty())
     <td>{{ $data->name ?? '' }}</td>
     <td>{{ $data->alias ?? '' }}</td>
     ...

Upvotes: 0

Views: 1046

Answers (2)

Niraj Kavishka
Niraj Kavishka

Reputation: 51

Use @if to check for NULL

@foreach ($attendance as $data)
    @if (!empty($data))
        <td>{{ $data->name ?? '' }}</td>
        <td>{{ $data->alias ?? '' }}</td>
        ...

Upvotes: 1

atma
atma

Reputation: 214

You can use 2 approach.

First, checking null data in loop by counting the array

// Blade
@foreach ($attendance as $data)
    @if (count($data) > 0)
     <td>{{ $data->name ?? '' }}</td>
     <td>{{ $data->alias ?? '' }}</td>
     ...
    @endif
@endforeach

Or, checking in database with Eloquent method whereNotNull, so null data will not appear in your blade variable

// Eloquent
Model::whereNotNull('column_name')

Laravel 8.x, Database: Query Builder, additional-where-clauses

Upvotes: 3

Related Questions