Laravel eloquent returning array of array

Asked

Viewed 940 times

1

I have this consultation using eloquent

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

and she 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’d like her to return

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

or something like that I don’t understand what I’m doing wrong

  • A simple way to get around the problem is to count the amount of elements of each date with the count php. Type count($x["06-Jul-"])

  • Is mysql?????...

  • You could edit the question and put the structure of the Logs table.

  • You asked for the list of ids in select, not the count (per day). The query has a method count for that reason.

2 answers

1


To group the data by day and month and count, you need to work with groupBy method of to group and count lines all this in commands that will bring the result without the expected layout, then use the method Transform 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']];
    });

References

1

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

Something like that:

$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);

Upshot

array(2) {
  ["06-Jul-"]=> int(1)
  ["07-Jul-"]=> int(3)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.