Harry Bosh
Harry Bosh

Reputation: 3790

Warning thrown: count(): Parameter must be an array or an object that implements Countable

While using "laravel/framework": "5.8.*",

I get the following error:

    $user = App\User::find(314);
    dump(PHP_VERSION);
    dump(is_object($user));
    dump(is_array($user));
    dump(count($user));
    dd($user);

I get the following error count(): Parameter must be an array or an object that implements Countable

However when I silence the warning. We get the correct output @dump(count($user));

"7.2.19"
true
false
1
User {#821 ▼
  #table: "users"
  #guarded: array:5 [▶]

....


Note: count() works when the collection has more than 1.

    $users = App\User::find([12,13,14,15,165,166,1666,133,11,111]);
    dump(PHP_VERSION);
    dump(is_object($user));
    dump(is_array($user));
    dump(count($user));
    dd($user);

output:

"7.2.19"
true
false
9
Collection {#825 ▼
  #items: array:9 [▶]
}

Upvotes: 0

Views: 1290

Answers (3)

Harry Bosh
Harry Bosh

Reputation: 3790

I found this to be the most useful for collections

if(count($user->toArray()) > 0)

perhaps a better way (untested)

count(($user ?? []))

Upvotes: 0

fingersandmind
fingersandmind

Reputation: 29

Why do you want to count a $user when you are only finding it by id? Of course it will only return either 1 or 0.

Upvotes: 0

MaartenDev
MaartenDev

Reputation: 5802

The count method isn't supported when the data returned can differ from array or object. An alternative would be to use a where statement that always returns an array when called:

$users = App\User::whereIn('id', [12,13,14,15,165,166,1666,133,11,111])->get();
var_dump($users);

Upvotes: 1

Related Questions