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:




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


Leave a reply

Your email address will not be published. Required fields are marked *