Reputation: 93
Can I use count($posts)
in Laravel to retrieve the number of elements in a collection, and how does it differ from $posts->count()
?
Thank you
Upvotes: 1
Views: 4894
Reputation: 887
In short it depend of the Laravel version you're using.
on laravel 5.5 for example i see the Collection class implement the countable interface so you could call count($posts)
but version 8 of laravel don't anymore implement it so you couldn't with this version.
Anyway you would get the same result using both function
UPDATE: as mentionned by @apokryfos the Collection
class implement Enumerable
so there is no difference and you can use both.
Upvotes: 2
Reputation: 1386
->get()->count()
will load Eloquent model objects into memory and then will count those.
->count()
will use DB aggregate function
simple php count(Model::all())
will also count the model objects already loaded which is not necessary
Upvotes: 2