351

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?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
bitinn
  • 9,188
  • 10
  • 38
  • 64

13 Answers13

719

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

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.

Community
  • 1
  • 1
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • 4
    thx, just to add that if you run query `first()`, the result is different from `get()`, which can be checked with `!$result` as empty result is `null` – bitinn Dec 14 '13 at 17:14
  • 2
    @btinn yes -- if you did i.e. `Model::first()` -- it's actually acting on the 'first` method of the query builder and NOT the collection, therefore it will pick the first one from the database -- however `Model::get()` will return an instance of Illuminate\Support\Collection so if you did `$r = Model::get()` and then `$r->first()` it will pick out the first item within that collection. – Gary Green Dec 14 '13 at 18:35
  • One thing this answer doesn't address is whether `count($result)` works; adding that detail would be an improvement. – Mark Amery Sep 25 '15 at 13:53
  • what's the difference between $result->count and count($result) Does $result->count hit the database again? If not, I guess these are the same then! – Kamy D Jan 08 '16 at 17:00
  • $result->count doesnt hit the database again as it uses the collection Facade helper function count() – Gokigooooks Feb 27 '16 at 01:32
  • !$result->isEmpty() isn't working for me in Laravel 5.2. – PapaHotelPapa Mar 23 '16 at 00:58
  • How about when you only one want to check whether a specific column (property) like in `$collection->column` is empty / null or not? – Pathros Mar 26 '16 at 02:07
  • 2
    @pathros There's no simple way of doing that. You would have to iterate through each member of the collection using a `foreach` loop and then use one of these checks (think: `count($collection->column)`). – PapaHotelPapa Apr 06 '16 at 19:44
  • great to know that first returns null if no record is found! – chiliNUT Sep 09 '16 at 21:05
  • Doesn't work for me, at least not on an empty collection. – Bert H Sep 26 '18 at 15:23
98

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

clod986
  • 2,527
  • 6
  • 28
  • 52
  • 1
    How about when you only one want to check whether a specific column (property) like in $collection->column is empty / null or not? – Pathros Mar 26 '16 at 02:08
20

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.

boroboris
  • 1,548
  • 1
  • 19
  • 32
sathish R
  • 402
  • 4
  • 8
17

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.
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
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.

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
9

I think better to used

$result->isEmpty();

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

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
7

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) { } 
pardeep
  • 359
  • 1
  • 5
  • 7
5

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.

Patrick Lumenus
  • 1,412
  • 1
  • 15
  • 29
1

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().

  • 5
    keeping it as a collection is actually convenient so that the objects returned can still inherit lots of useful function in the collection facade. – Gokigooooks Feb 27 '16 at 01:30
1

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

Nazmul Haque
  • 720
  • 8
  • 13
1

now you can use

$query = Model::where(...);
$isExists = $query->exists();
$count = $query->count();

https://laravel.com/docs/10.x/queries#determining-if-records-exist https://laravel.com/docs/10.x/queries#aggregates

chai
  • 186
  • 10
0

You want to check these two cases of count().

#1

If the result contains only a single row (one record) from the database by using ->first().

if(count($result)) {
    // record is exist true...
}

#2

If result contain set of multiple row (multiple records) by using ->get() or ->all().

if($result->count()) {
    //record is exist true...
}
francisco
  • 1,387
  • 2
  • 12
  • 23
Ravindra Bhanderi
  • 2,478
  • 4
  • 17
  • 29
0

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);
}
francisco
  • 1,387
  • 2
  • 12
  • 23
Ayomikun Samuel
  • 125
  • 2
  • 9