Skip to content
Advertisement

Laravel Distinct Count

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.

Advertisement

Answer

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');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement