Laravel check if collection is empty Laravel check if collection is empty php php

Laravel check if collection is empty


To determine if there are any results you can do any of the following:

if ($mentor->first()) { } if (!$mentor->isEmpty()) { }if ($mentor->count()) { }if (count($mentor)) { }if ($mentor->isNotEmpty()) { }

Notes / References

->first()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_first

isEmpty() https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

->count()

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

count($mentors) works because the Collection implements Countable and an internal count() method:

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Collection.html#method_count

isNotEmpty()

https://laravel.com/docs/5.7/collections#method-isnotempty

So what you can do is :

if (!$mentors->intern->employee->isEmpty()) { }


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


Starting from Laravel 5.3 you can simply use :

if ($mentor->isNotEmpty()) {//do something.}

Documentation https://laravel.com/docs/5.5/collections#method-isnotempty