How to check if a collection is not empty in Laravel

Categorized as Laravel Tagged

You may ask, why the expression !empty($collection) fails to work (could be a controller or a blade view). The answer is that you have to check the empty state of the collection a bit differently in Laravel. Here is the code:

if ($collection->first()) { ... } 

if (!$collection->isEmpty()) { ... }

if ($collection->count()) { ... }

if (collection($collection)) { ... }

if ($collection->isNotEmpty()) { ... }

I would prefer the last method as the most self-explanatory one, and it doesn’t need any code comment.

Notes on Laravel methods:

->first() https://laravel.com/docs/9.x/collections#method-first

->isEmpty() https://laravel.com/docs/9.x/collections#method-isempty

->count() https://laravel.com/docs/9.x/collections#method-count

The count($collection) method works as the Collection implements Countable and its internal count() method.

->isNotEmpty() https://laravel.com/docs/9.x/collections#method-isnotempty

Leave a reply

Your email address will not be published.