Laravel distinct count

Any way to make this request work with laravel? DB :: raw or Eloquent does not matter.

SELECT count(DISTINCT name) FROM tablename;

Here is what I tried but cannot get the correct output:

EloquentTableName::select(DB::raw('count(DISTINCT name) as name_count'))->get();

This returns something like this, and I would like to fix it:

([{"name_count":"15"}])

I just want to get a score of 15.

+4
source share
2 answers

you can simply replace get with count like this:

$count = DB::table('tablename')->count(DB::raw('DISTINCT name'));

can also do:

DB::table('tablename')->distinct('name')->count('name');
+13
source

Try the following:

$result = TableName::groupBy('name')->count();

Hope this helps ...

0
source

All Articles