Here's what's going on with the code you have there:
1.When callingUser::all()
you'll get aIlluminate\Database\Eloquent\Collection
on which you can callcount
which counts the elements in the collection like so:
public function count()
{
return count($this->items);
}
This will return the number of items in the collection as you correctly expected.
2.When callingUser::find(2)
however, the Eloquent Query Builder will not return aCollection
, because it will check to see how many results there are, and since you passedone IDyou'll get at mostone result, so it will return an Eloquent Model instead. The Model does not have acount()
method, so when you try to call$coll->count();
it will go to the magic__call
method that the class has implemented which looks like this:
public function __call($method, $parameters)
{
if (in_array($method, array('increment', 'decrement')))
{
return call_user_func_array(array($this, $method), $parameters);
}
$query = $this->newQuery();
return call_user_func_array(array($query, $method), $parameters);
}
As you can see the method tries to see if it should call a couple of hardcoded methods (increment
anddecrement
), which of course don't match in this case because$method = 'count'
, so it continues to create a new Query on which it will call thecount
method.
The bottom line is that both the first and second code samples end up doing the same thing:counting all the entries in theusers
table.
And since, as I pointed our above, one ID cannot match more than one row (since IDs are unique), theanswer to your questionis that there's no need or way to count the results offind(2)
, since it can only be 0 (ifnull
is returned) or 1 (if aModel
is returned).
UPDATE
First of all, for future reference you can use the PHPget_class
to determine the class name of an object orget_parent_class
to determine the class it is extending. In your case the second functionget_parent_class
might be useful for determining the model class since theUser
class extends a Laravel abstract Model class.
So if you have a modelget_class($coll)
will reportUser
, butget_parent_class($coll)
will report\Illuminate\Database\Eloquent\Model
.
Now to check if the result is a Collection or a Model you can useinstanceof
:
instanceof
is used to determine whether a PHP variable is an instantiated object of a certain class
Your checks should look something like this:
// Check if it's a Collection
if ($coll instanceof \Illuminate\Support\Collection)
// Check if it's a Model
if ($coll instanceof \Illuminate\Database\Eloquent\Model)
You might also want to check if the result isnull
, sincefind
will returnnull
if no entry is found with the given ID:
if (is_null($coll))
::find()
id = 2
::find(2)