Eloquent Collection: Counting and Detect Empty

2019-01-04 04:59发布

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?

9条回答
甜甜的少女心
2楼-- · 2019-01-04 05:23

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.
查看更多
再贱就再见
3楼-- · 2019-01-04 05:25

You can do

$result = Model::where(...)->count(); 

to count the results.

You can also use

if ($result->isEmpty()){}

to check whether or not the result is empty.

查看更多
男人必须洒脱
4楼-- · 2019-01-04 05:31

I think you are looking for:

$result->isEmpty()

This is different from empty($result), which will not be true because the result will be an empty collection. Your suggestion of count($result) is also a good solution. I cannot find any reference in the docs

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-04 05:32

------SOLVED------

in this case you want to check two type of count for two cace

case 1:

if result contain only one record other word select single row from database using ->first()

 if(count($result)){

       ...record is exist true...
  }

case 2:

if result contain set of multiple row other word using ->get() or ->all()

  if($result->count()) {

         ...record is exist true...
  }
查看更多
ら.Afraid
6楼-- · 2019-01-04 05:33

I think better to used

$result->isEmpty();

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

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-04 05:37

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) { } 
查看更多
登录 后发表回答