Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 547
Jamie Avatar asked Mar 07 '16 08:03

Jamie


1 Answers

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()) { } 
like image 200
Drudge Rajen Avatar answered Sep 25 '22 02:09

Drudge Rajen