28
votes

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.

4
can you clarify the difference between current output and expected output? - Gouda Elalfy
@GoudaElalfy i just need to get the int value. I need 15. What i've got is "name_count":"15" - saimcan
What if you do ->only("name_count") instead of ->get() ? - apokryfos

4 Answers

69
votes

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

You may simply do the following:

Tablename::distinct()->count('name');
5
votes
DB::table('tablename')->distinct()->count('name');

is the correct answer.

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

1
votes

you can do this as smoothly as honey

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

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