laravel ->count() vs ->get()->count() laravel ->count() vs ->get()->count() laravel laravel

laravel ->count() vs ->get()->count()


->get()->count() will load Eloquent model objects into memory and then will count those.

->count() will use DB aggregate function, so it will definitely be more efficient:

select count(*) as aggregate ...


It's quite late answer but I had faced the same issue. These two examples are returning two different counts because of groupBy you have used.

$progress = $this->user->userActivities()->select('date')            ->groupBy('date')            ->get()->count();

This takes the rows first, then count the row numbers and returns the count.

$progress =  $this->user->userActivities()->select('date')            ->groupBy('date')            ->count();

Whereas this counts the rows by its group in the DB and returns the first group's row record count only from the list.

the solution I used instead of get()->count() for my case is like

$progress =  $this->user->userActivities()            ->distinct('date')            ->count('date');


Use ->get()->count() is wrong. I used ->get()->count() in my web app and when my database records have more than 80000 records I get error 500 in my app.