0

I have been already to this link but its different in my case.

I have record which has a column created_at. My objective is to group the record by year, and inside each year, records should be group in month also.

My expectations:

enter image description here


I have tried this code below, but it is working only for yearly only.

$records = \App\VehicleRental::query()
    ->where('operator_id', $operator->id)
    ->get()
    ->groupBy(function($val) { return \Carbon\Carbon::parse($val->created_at)->format('Y'); });

So I have tried to put another group for month but error Property [created_at] does not exist on this collection instance. returned

$record = \App\VehicleRental::query()
    ->where('operator_id', $operator->id)
    ->get()
    ->groupBy(function($val) { return \Carbon\Carbon::parse($val->created_at)->format('M'); })
    ->groupBy(function($val) { return \Carbon\Carbon::parse($val->created_at)->format('Y'); });


Someone knows how to achieve this?
charles
  • 364
  • 6
  • 18

1 Answers1

0

You could also pass an array of elements to the groupBy() collection method, for nested grouping. Try this:

$record = \App\VehicleRental::query()
    ->where('operator_id', $operator->id)
    ->get()
    ->groupBy([
        function ($val) { return $val->created_at->format('Y'); },
        function ($val) { return $val->created_at->format('m'); },
    ]);

As a side note, the created_at could be directly casted as a Carbon instance. If the above doesn't work, define the attribute date mutator in your model:

# VehicleRental.php

protected $dates = ['created_at', 'updated_at'];
Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
  • Sir the months are not sorted. No ideas how to append `->sortBy(created_at)` could you do me that favor – charles Feb 13 '20 at 17:35
  • Then sort it first: `\App\VehicleRental::query()->orderBy('created_at')->where(...)->get()->[...]` – Kenny Horna Feb 13 '20 at 17:36
  • @charles you didn't mention any `log_in` in your question. Update your post to see the logic in there. – Kenny Horna Feb 13 '20 at 17:38
  • it is `created_at` Sir. lots of tabs here sorry. by the I tried `->orderBy('created_at') ->get() ->groupBy(` but still months are not sorted. Only the year – charles Feb 13 '20 at 17:40