Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Laravel return array not working with empty() But worked with count()

Tags:

php

count

laravel

I am working with laravel framework project and facing below issue.

Query:

$query = DB::table('test');
$query->select('*');
$query->where('testId = 1');
$result = $query->get();
print_r($result);

Output :

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
        )

)

Now I am checking $result have record or not.

if(empty($result))
{
   echo "Not Empty check with empty()";
}

if(count($result) == 0)
{
   echo "Not Empty check with count()";
}

Output:

Not Empty check with count()

Question :

I have used empty() in all the projects but in laravel framework project I am not able to know that why this $result going in count() condition and not going in empty().

Note:

I have read that count() is slow compare to empty() also empty() check variable is set or not so I am using empty() in all return array or object array.

Please help someone.

Thanks in advance!

like image 897
RJParikh Avatar asked Oct 23 '25 21:10

RJParikh


1 Answers

If you use collection, you sould use isEmpty() method

docs: https://laravel.com/docs/5.4/collections#method-isempty

like image 131
misterdebug Avatar answered Oct 26 '25 11:10

misterdebug