skip to Main Content

I want to get data plan by date, then I use carbon on laravel to get it.
this my query on laravel controller

 $data = DB::table('visit_plan')
                ->join('outlets', 'outlets.id', '=', 'visit_plan.id_outlet')
                ->select('outlets.id', 'outlets.name')
                ->get()
                ->groupBy(function($date) {
                    return $this->attributes['date'] = Carbon::parse($date->date)->format('Y-m-d');
                });
               

    $data = $data->reverse();

The output json like this :

{
"2023-08-29": [
    {
        "id": "0e2b7c5b-c8d4-4c03-bec8-69d9eeeb7e4b",
        "name": "Basura Mall",
    },
    {
        "id": "0e2b7c5b-c8d4-4c03-bec8-69d9eeeb7e4b",
        "name": "TRANSMART KOKAS",

    }
]

}

But i want key in date value and event value like this :

{
        "tanggal": "2023-08-29",
        "event": [
            {
                "id": "01dfcdef-691c-43aa-a167-cb91b153a7e8",
                "name": "Bassura Mall "
            },
            {
                "id": "d494cdf4-7c79-4e7a-9761-c37203b7ba9c",
                "name": "TRANSMART KOKAS"
            },
            
        ]
    }

2

Answers


  1. You can map your data to your wished structure. Due to it being left out mostly, the second parameter of closures on map, each and similar is the key of the array. Which you can use to get the grouped by key.

    return $data->map(function ($events, $key) {
        return [
            'tanggal' => $key,
            'event' => $events,
        ];
    });
    

    A more Laravel approach is to make a setup that use Laravel resources to do theses transformations. For the scope of this question is a little over engineered.

    Login or Signup to reply.
  2. You can get your result like this.

    $data = $data->toArray();
    $tanggal = array_keys($data)[0];
    $event = array_values($data)[0];
    $data = [
      'tanggal' => $tanggal,
      'event' => $event,
    ];
    return $data;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search