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

51,502

Solution 1

->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 ...

Solution 2

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');

Solution 3

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.

Solution 4

$count = Model::all()->count();
return view('home',compact('count'));

this will function for laravel 6;

Solution 5

The first counts the number of returned records, the second counts the records and returns the number. If you are using a paging of 10, for example, then the first will yield 10 and the second the actual number if the number of mathcing elements is greater than 10.

Share:
51,502
Chris
Author by

Chris

Updated on July 27, 2022

Comments

  • Chris
    Chris almost 2 years

    Why are the two statement below behaving differentlY? The first returns 3 the second returns 1 for $progress. I thought that the first aggregates on the DB and the second on the server. So they should still return the same value.

    $progress = $this->user->userActivities()->select('date')
                    ->groupBy('date')
                    ->get()->count();
    
    $progress =  $this->user->userActivities()->select('date')
                    ->groupBy('date')
                    ->count();
    
  • Vytenis Ščiukas
    Vytenis Ščiukas over 2 years
    Not the same, one ->count() gets database count (COUNT) and ->get()->count() returns collection count. Most of the time they return the same number, but functionally they are not the same.