Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 483
saimcan Avatar asked Mar 08 '16 13:03

saimcan


People also ask

What is distinct () in Laravel?

In Laravel, the distinct() method is used to fetch distinct records from the database, it is also part of Laravel query builder, which means it can be chained to other query builder methods as well. The typical usage of this method is to find how many users made comments on a post.

How to get distinct values from a table in Laravel?

$users = User::select('name')->groupBy('name')->get()->toArray() ; groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them.

How to use distinct in Laravel query?

What is Laravel Distinct? As mentioned in the previous paragraph, the Laravel statement of DISTINCT is a query that identifies the exact value of the search. It returns the value from the database through the following Eloquent Distinct method: DB::table('tablename')->distinct('name')->count('name');

What is distinct count?

Count is the total number of values. Count Distinct in the number of unique values. Count Distinct will always be equal to or less than Count. 1 Helpful. Share.


1 Answers

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'); 
like image 194
Gouda Elalfy Avatar answered Sep 20 '22 02:09

Gouda Elalfy