I have an orders table where there is a status column.
I am trying to get the count of each status like this :
$pending = Order::where('status','=','pending')->count();
$active = Order::where('status','=','active')->count();
But this is not efficient as am having to make one call for each status type.
How can I reduce number of queries ?
$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.
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.
To make an SQL request:
SELECT count(DISTINCT `status_id`) FROM `dbname`.orders WHERE `user_id` = '2';
In Laravel you can try the following:
$user->orders()->distinct()->count(["status_id"]);
You could try
$orders = Order::select(DB::raw('count(*) as order_count, status'))
->groupBy('status')
->get();
here is the way you write ->
$users= DB::table('table_name')->distinct()->get(['column_name']);
$users_count = $users->count();
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