Spread the love

In this article we will learn collection count and detect or check empty eloquent collection in laravel. Laravel collection is used to simplify the operations of array. Illuminate\Support\Collection library is used to handle the collection and arrays in laravel. Laravel heavily used collections in eloquent query builder to result the output so sometimes we also want to check if the result is empty or not in laravel.

This example will work in all version of laravel including laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9. In this example we will use collect and count methods of collection library.

Also Read : How to use Laravel count rows with example ?

To check the collection is empty or not we can simply use as follow

$Post = new Post::where("status",1)->get(); 
$Post->isEmpty();

There is several ways to check the empty of collection let’s check the all methods of Collection Count and Check Empty Eloquent Collection in Laravel

Method 1 : Collection isEmpty method

In this method we will simply use the isEmpty method of collection the check the model has data or not

$Post = new Post::where("status",1)->get(); 
$Post->isEmpty();

Method 2 : Collection isNotEmpty method

In this method we will simply use the isNotEmpty method of collection the check the model has data or not. isNotEmpty is opposite of isEmpty method

$Post = new Post::where("status",1)->get(); 
if($Post->isNotEmpty())
{
  // run other checks
}

Method 3 : Collection count method

In this method we will simply use the count method of collection to get the count of result.

$Post = new Post::where("status",1)->get(); 
if($Post->count()>0)
{
  // run other checks
}

Leave a Reply