PASSWORD RESET

Your destination for complete Tech news

PHP

How to check if the collection is empty in Laravel?

388 0
< 1 min read

In Laravel, you can use the isEmpty method of the Collection class to check if a collection is empty.

Here’s an example of how you can use it:

$collection = collect([1, 2, 3]);
if ($collection->isEmpty()) {
    // Collection is empty
} else {
    // Collection is not empty
}

You can also use the isNotEmpty method to check if a collection is not empty:

$collection = collect([1, 2, 3]);
if ($collection->isNotEmpty()) {
    // Collection is not empty
} else {
    // Collection is empty
}

You can also use the isEmpty method in a chain of method calls:

$collection = collect([1, 2, 3])
    ->filter(function ($item) { return $item > 2; })
    ->isEmpty();

if ($collection) {
    // Filtered collection is empty
} else {
    // Filtered collection is not empty
}

Note that the isEmpty method returns a boolean value indicating whether the collection is empty or not. It does not modify the collection itself.

Leave A Reply

Your email address will not be published.

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