PASSWORD RESET

Your destination for complete Tech news

How to check if a collection is empty in Laravel?

1.04K 0
< 1 min read

To check if a Laravel collection is empty, you can use the isEmpty method. This method will return true if the collection is empty, and false if it is not.

Here’s an example:

$collection = collect([]);
$empty = $collection->isEmpty();

// $empty is now true

$collection = collect([1, 2, 3]);
$empty = $collection->isEmpty();

// $empty is now false

You can also use the isNotEmpty method, which is the opposite of the isEmpty method and will return true if the collection is not empty and false if it is.

$collection = collect([]);
$notEmpty = $collection->isNotEmpty();

// $notEmpty is now false

$collection = collect([1, 2, 3]);
$notEmpty = $collection->isNotEmpty();

// $notEmpty is now true

Alternatively, you can use the count method to check if the collection is empty:

$collection = collect([]);
$empty = $collection->count() == 0;

// $empty is now true

$collection = collect([1, 2, 3]);
$empty = $collection->count() == 0;

// $empty is now false

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.