6 months ago

Count records by field

Posted 6 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'))
  ->mapWithKeys(function($item) {
        return [$item['type'] => $item['count']];

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.