This laravel quick tutorial helps to understand Laravel collection is empty or not. The laravel collection is used to store data with arrays of data. The collections are immutable, which Means every Collection method returns an entirely new Collection instance.
Immutable collections can’t be changed at all. They have their own elements. The laravel collection will have two methods to check collection is empty or not.
You can also check other recommended tutorials of Lumen/Laravel,
- How to Monitor Beanstalkd Queue In Laravel Using Admin Console
- How to Configure supervisord on Linux for Laravel Jobs Queue
- How to Configure Memcached in Lumen Api Framework
- Simple Example of Laravel 5 Login System Using Sentry
- Simple Laravel Layouts using Blade Template and Bootstrap Theme
You can use these methods with any version laravel 8 and laravel 9 applications. I will give you simple examples of isEmpty()
and isNotEmpty()
collection in laravel.
Laravel Collection isEmpty() Example
Let’s take a simple collection example to check is empty or not using isEmpty() method.
Syntax:
$collecton->isEmpty();
Laravel isEmpty() Example
public function index() { $collection = collect([]); $res = $collection->isEmpty(); }
Output:
true
Laravel Collection isNotEmpty() Example
Let’s check laravel collection is not empty using isNotEmpty()
method.
Syntax:
$collecton->isNotEmpty();
Laravel isNotEmpty Example
public function index() { $collection = collect([]); $output = $collection->isNotEmpty(); }
Output:
false