phplaravellaravel-5

Laravel check if collection is empty


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.


Solution

  • You can always count the collection. For example $mentor->intern->count() will return how many intern does a mentor have.

    https://laravel.com/docs/5.2/collections#method-count

    In your code you can do something like this

    foreach($mentors as $mentor)
        @if($mentor->intern->count() > 0)
        @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
        @else
            Mentor don't have any intern
        @endif
    @endforeach