Laravel check if collection is empty

Viewed 268063

I've got this in my Laravel webapp:

@foreach($mentors as $mentor)
    @foreach($mentor->intern 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
@endforeach

How could I check if there are any $mentors->intern->employee ?

When I do :

@if(count($mentors))

It does not check for that.

8 Answers

This is the best solution I found so far.

in blade

@if($mentors->count() == 0)
    <td colspan="5" class="text-center">
        Nothing Found
    </td>
@endif

in controller

if ($mentors->count() == 0) {
    return "Nothing Found";
}

From php7 you can use Null Coalesce Opperator:

$employee = $mentors->intern ?? $mentors->intern->employee

This will return Null or the employee.

I prefer

(!$mentor)

Is more effective and accurate

First you can convert your collection to an array. Next run an empty method like this:

if(empty($collect->toArray())){}
Related