Laravel Distinct Count

Viewed 51044

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 Answers
DB::table('tablename')->distinct()->count('name');

is the correct answer.

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

You may simply do the following:

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

you can do this as smoothly as honey

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

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

Related