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.
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.
$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.
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');
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With