Eloquent Collection: Counting and Detect Empty

Viewed 412604

This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from $result = Model::where(...)->get() is empty, as well as counting the number of elements.

We are currently using !$result to detect empty result, is that sufficient? As for count($result), does it actually cover all cases, including empty result?

12 Answers

There are several methods given in Laravel for checking results count/check empty/not empty:

$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.

I think better to used

$result->isEmpty();

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

I think you try something like

  @if(!$result->isEmpty())
         // $result is not empty
    @else
        // $result is empty
    @endif

or also use

if (!$result) { }
if ($result) { } 

According to Laravel Documentation states you can use this way:

$result->isEmpty();

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

You can use: $counter = count($datas);

The in_array() checks if a value exists in an array.

public function isAbsolutelyEmpty($value)
{
   return in_array($value, ["", "0", null, 0, 0.0], true);
}
Related