40

Any way to make this query work using laravel? DB::raw or Eloquent usage doesn't matter.

SELECT count(DISTINCT name) FROM tablename;

Here's what i've tried but cannot get the proper output:

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

This returns something like this and i'd like to fix that:

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

I just want to get count 15.

saimcan
  • 1,706
  • 7
  • 32
  • 64

4 Answers4

91

you can simply replace get with count in this way:

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

also can do:

DB::table('tablename')->distinct('name')->count('name');
Gouda Elalfy
  • 6,888
  • 1
  • 26
  • 38
12
DB::table('tablename')->distinct()->count('name');

is the correct answer.

->distinct('name') does not work in Laravel.

m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
Chandan Mistry
  • 191
  • 2
  • 5
7

You may simply do the following:

Tablename::distinct()->count('name');
4

you can do this as smoothly as honey

Modal::('yourTable')->distinct()->count('yourAttribute')

and it will fetch unique count number of 'yourAttribute'.

saimcan
  • 1,706
  • 7
  • 32
  • 64