Laravel Distinct Count

44,181

Solution 1

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

Solution 2

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

is the correct answer.

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

Solution 3

You may simply do the following:

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

Solution 4

you can do this as smoothly as honey

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

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

Share:
44,181
saimcan
Author by

saimcan

Updated on January 28, 2021

Comments

  • saimcan
    saimcan over 3 years

    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.