laravellaravel-collection

Laravel grouped collection returns object instead of array


I have the following query

$outings = Outing::all()->groupBy(function ($item) {
   return Carbon::parse($item['start'])->format('m/d/Y');
});

return response()->json([
    'outings' => $outings
], 200);

The response is returning an object and I need it to return an array As you can see, outings is an object and not an array

How can I get outings to be an array instead of an object.

If I don't group the collection and just do

Outing::all();

It will return an array rather than an object. The Group by is doing something weird.

If I DD($outings) it does in fact return a collection, so I think it's odd that it gets cast to an object when returned to the browser rather than an array.

Below is the output when I DD($outings->toArray())

enter image description here

Thanks


Solution

  • If you want array then use this

    $outings = Outing::all()->groupBy(function ($item) {
       return Carbon::parse($item['start'])->format('m/d/Y');
    })->map(function($item){
        return $item->all();
    });
    
    return response()->json($outings, 200);
    

    If you want date as key then

    $outings = Outing::all()->groupBy(function ($item) {
       return Carbon::parse($item['start'])->format('m/d/Y');
    });
    
    return response()->json($outings->toArray(), 200);