yemilgr
3 months ago

Count records by field

Posted 3 months ago by yemilgr

I'm looking the best way to get and array that count existent rows of some eloquent model by a certain field. Guest an Installation model with a type field. Right now Iam using this approach to do it

$typeCount = Installation::select('type', DB::raw('COUNT(*) as count'))
  ->groupBy('type')
  ->get()
  ->mapWithKeys(function($item) {
        return [$item['type'] => $item['count']];
  })->toArray();

and $typeCount will return an array like this

[
     "contrib" => 2,
     "official" => 1,
]

Is there a better way or an elegant one????

Please sign in or create an account to participate in this conversation.