Eloquent Collection: Counting and Detect Empty

怎甘沉沦 提交于 2019-11-26 04:29:32

问题


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?


回答1:


When using ->get() you cannot simply use any of the below:

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

Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }

You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.

$result = Model::where(...)->first();
if ($result) { ... }

Notes / References

  • ->first() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_first
  • isEmpty() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty
  • ->count() http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
  • count($result) works because the Collection implements Countable and an internal count() method: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count

Bonus Information

The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all()) and experimenting to see what classes it's actually returning (with help of get_class(...)). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.

  • Laravel 5.2 Collection Class
  • Laravel 5.2 Query Builder



回答2:


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




回答3:


I agree the above approved answer. But usually I use $results->isNotEmpty() method as given below.

if($results->isNotEmpty())
{
//do something
}

It's more verbose than if(!results->isEmpty()) because sometimes we forget to add '!' in front which may result in unwanted error.

Note that this method exists from version 5.3 onwards.




回答4:


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.



回答5:


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) { } 



回答6:


I think better to used

$result->isEmpty();

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




回答7:


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.




回答8:


so Laravel actually returns a collection when just using Model::all(); you don't want a collection you want an array so you can type set it. (array)Model::all(); then you can use array_filter to return the results

$models = (array)Model::all()
$models = array_filter($models);
if(empty($models))
{
 do something
}

this will also allow you to do things like count().




回答9:


------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...
  }



回答10:


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.



来源:https://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!