Laravel eloquent returning array array

1

I have this query using eloquent

$data= \App\Logs::select('id', 'created_at') 
    ->get()         
    ->groupBy(function($val) {
        return Carbon::parse($val->created_at)->format('d-M-');
    })->toArray();

and it returns this

array:2 [▼
  "06-Jul-" => array:1 [▼
    0 => array:2 [▼
      "id" => 1
      "created_at" => "2017-07-06 13:21:15"
    ]
  ]
  "07-Jul-" => array:3 [▼
    0 => array:2 [▼
      "id" => 2
      "created_at" => "2017-07-07 13:43:23"
    ]
    1 => array:2 [▼
      "id" => 3
      "created_at" => "2017-07-07 14:18:36"
    ]
    2 => array:2 [▼
      "id" => 4
      "created_at" => "2017-07-07 14:18:41"
    ]
  ]
]

When I would like it to return

"06-Jul-" => "1"
"07-Jul-" => "3" 

or something like this I'm not understanding what I'm doing wrong.

    
asked by anonymous 07.07.2017 / 17:23

2 answers

1

To group your data by day and month and count, you need to work with groupBy to group and count the rows all in commands that will bring the result without the expected layout, then use the transform method to format the output with the following example > :

$data= \App\Logs::select(\DB::raw('count(id),date(created_at)'))               
    ->groupBy('date(created_at)')
    ->get()
    ->transform(function($item, $key)
    {
      return [\Carbon\Carbon::parse($item['date(created_at)'])
          ->format('d-M-') => $item['count']];
    });

09.07.2017 / 03:10
1

Guilherme, I know your question was specific about the query in eloquent . But without the bank's structure it is difficult to help you. A palliative solution would be to use array_map in the result to format the output of the query information.

Something like this:

$array = [
    '06-Jul-' => [

            [
                "id" => 1,
                "created_at" => "2017-07-06 13:21:15"
            ]
        ],
    '07-Jul-' => [
            [
                "id" => 2,
                "created_at" => "2017-07-07 13:43:23"
            ],
            [
                "id" => 3,
                "created_at" => "2017-07-07 14:18:36"
            ],
            [
                "id" => 4,
                "created_at" => "2017-07-07 14:18:41"
            ]
        ]
];

$array = array_map(function($item){
    return count($item);
}, $array);

var_dump($array);

Result

array(2) {
  ["06-Jul-"]=> int(1)
  ["07-Jul-"]=> int(3)
}
    
07.07.2017 / 20:24