0

I've grouped a list of records by the month they were created in:

$jobListings = JobListing::with('company')->orderBy('created_at')->get();

$jobListings = $jobListings->groupBy(function($j) {
    return Carbon::parse($j->created_at)->format('m');
});

return response()->json($jobListings);

This will give me a JSON object that has records keyed by month in numerical format:

{
  "03": [...],
  "04": [...],
}

How can I change the keys of this Eloquent collection so that the months read as words like "March" and "April"?

To be clear, what I'd like to output is:

{
  "March": [...],
  "April": [...],
}

This answer shows how to convert the numbers to months.

How do I change the keys on this collection after running the groupBy?

Connor Leech
  • 18,052
  • 30
  • 105
  • 150

1 Answers1

4

You could try using format('F')

         return Carbon::parse($j->created_at)->format('F');
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • @J.A.Streich for the order the OP should add an explict order by clause based on format('m') .. – ScaisEdge Apr 24 '19 at 19:43
  • I was asking if that was strictly necessary here. As the objects were already sorted by the create_at prior to the groupBy; and they were in order with the previous groupBy... So, I was curious if your answer maintains the groupBy of the OP or if another sortBy is necessary with this change. – J. A. Streich Apr 24 '19 at 19:50
  • The group by return (a natural) sort based on the value returned .. in this case return the string name and not order byb the month order sequence .. – ScaisEdge Apr 24 '19 at 19:58
  • 1
    `Carbon::parse()` is not needed here because eloquent is already parse it into Carbon instance. Use directly. `$j->created_at->format('F')` – Rutvij Kothari Apr 24 '19 at 20:08