Laravel check if collection is empty

Laravel check if collection is empty

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Checking if a Nested Collection is Empty in Laravel

When you are iterating through nested relationships like $mentors and $mentor->intern, checking for existence isn't as simple as looking at the top-level collection. Your initial attempt using @if(count($mentors)) only validates that the outer list of mentors exists; it provides zero insight into whether any of those mentors actually possess internships, or if those intern records contain valid employee data.

In your specific Blade template, you are attempting to access a deeply nested property: $mentor->intern->employee. To determine if you should render this loop at all—or if you need to guard against UndefinedPropertyException—you must evaluate the collection at every level of nesting.

The Problem with Shallow Checks

The core issue with checking count($mentors) is that it ignores the state of the relationships attached to those models. In Laravel, when you eager load a relationship like $mentor->intern, the result is typically a Collection (or an array if not explicitly cast). If no internships exist for a mentor, this relationship collection will be empty.

However, simply checking the top-level count does not tell you if any valid row exists inside the nested structure. Furthermore, accessing $mentor->intern->employee assumes that every item in the $mentor->intern collection has an employee property. If the eager loading strategy returns a relationship model where the foreign key is null, or if the relationship itself hasn't been loaded correctly, directly accessing child properties can lead to errors.

Evaluating Nested Collections

To accurately check if there are any mentors with interns who have employees, you need to filter down through the hierarchy before rendering. You cannot rely on a single if statement at the root because the emptiness is conditional at each layer.

Here is a robust approach using Laravel's collection methods:

@if($mentors->whereNotNull('interns')->isEmpty() === false)
    @foreach($mentors as $mentor)
        @if(count($mentor->interns) > 0)
            <tr class="table-row-link" data-href="/werknemer/{{ $mentor->interns[0]->employee->EmployeeId }}">
                <td>{{ $mentor->interns[0]->employee->FirstName }}</td>
                <td>{{ $mentor->interns[0]->employee->LastName }}</td>
            </tr>
        @endif
    @endforeach
@endif

Note the shift in logic: we first check if the mentor collection contains any entries where the interns relationship is populated. Then, inside the loop, we verify that the specific $mentor->interns collection has a count greater than zero before attempting to access the employee data.

Handling Empty Relationships Safely

A common pitfall occurs when you assume $mentor->intern returns an object or a collection where you can blindly iterate. In standard Eloquent relationships, if no records match, the relationship usually resolves to an empty Collection. If your relationship definition uses hasOne or hasManyThrough, the behavior might differ slightly, but the principle remains: always validate the count before accessing properties of the items inside.

If you need to check for the existence of any employee across all mentors and interns without rendering a table row immediately, you can flatten the collection first:

@php
    $validEntries = collect($mentors)
        ->filter(fn($mentor) => count($mentor->interns) > 0)
        ->flatMap(fn($mentor) => $mentor->interns)
        ->whereNotNull('employee')
        ->toArray();
@endphp

@if(count($validEntries) > 0)
    <table>
        @foreach($validEntries as $intern)
            <tr class="table-row-link" data-href="/werknemer/{{ $intern->employee->EmployeeId }}">
                <td>{{ $intern->employee->FirstName }}</td>
                <td>{{ $intern->employee->LastName }}</td>
            </tr>
        @endforeach
    </table>
@endif

This pattern uses filter to remove mentors without interns and flatMap to extract only the intern records, ensuring you never attempt to access $intern->employee on a null record.

Eager Loading Considerations

It is also worth noting how you are fetching this data in your controller or resolver. If you rely on lazy loading without explicit constraints, accessing $mentor->intern inside a loop can trigger N+1 query issues if not handled carefully with with(). Ensure you are eager loading these relationships when fetching the mentors list to maintain performance while checking counts:

$mentors = Mentor::with(['interns.employee'])->get();

By eagerly loading both levels, you guarantee that $mentor->intern and $mentor->intern->employee are populated (or null) in memory, making your count() checks reliable and avoiding database hits during the view rendering phase.

Final Recommendation

Always validate the intermediate layers of your nested relationships. Checking only the top-level collection is insufficient for deep hierarchies. By filtering out empty relationships before iteration, you prevent runtime exceptions and ensure your Blade template renders only when valid data exists across the entire chain.

Our network