[laravel] Eloquent Collection: Counting and Detect Empty

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?

This question is related to laravel laravel-4 eloquent laravel-collection

The answer is


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


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.


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


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

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.

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.


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.


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


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

I think better to used

$result->isEmpty();

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


Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()

Examples related to laravel-collection

How to Merge Two Eloquent Collections? Eloquent Collection: Counting and Detect Empty