Search code examples
laraveleloquentcollect

Laravel Grouping By date


i read some questions already posted here.But not found any solution for my requirement. Remember this response showing check-in info about user visited a store.

Grouping the Collect

$this->collection->groupBy(function ($date) {
                return Carbon::parse($date->createdAt)->toDateString();
  }

Will returning the data grouping by date..

response

{
   "data":{
      "2021-08-31":[
         {
            "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
            "name":"General Shop 15"
         },
         {
            "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
            "name":"General Shop 15"
         }
      ],
      "2021-08-29":[
         {
            "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
            "name":"General Shop 15"
         }
      ],
      "2021-08-20":[
         {
            "avatar":"avatars/GSDrGe8RLGXykvvsEVlWtnqRGbAOoJUuSh7WZhFc.jpg",
            "name":"XYZ Store"
         },
         {
            "avatar":"avatars/GSDrGe8RLGXykvvsEVlWtnqRGbAOoJUuSh7WZhFc.jpg",
            "name":"XYZ Store"
         },
         {
            "avatar":"avatars/GSDrGe8RLGXykvvsEVlWtnqRGbAOoJUuSh7WZhFc.jpg",
            "name":"XYZ Store"
         }
      ]
   }
}

But I want response look like blew.. then grouping date will show as..

{
   "data":[
      {
         "date":"2021-08-31",
         "data":[
            {
               "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
               "name":"General Shop 15"
            },
            {
               "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
               "name":"General Shop 15"
            }
         ]
      },
      {
         "date":"2021-08-29",
         "data":[
            {
               "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
               "name":"General Shop 15"
            },
            {
               "avatar":"avatars/IIa1gvCvww5K4geXJHUYTTZm2IKFoK113octfPB1.jpg",
               "name":"General Shop 15"
            }
         ]
      }
   ]
}

Solution

  • You are already receiving the data you require. just to fix the data in the required format loop the collection you received and put it in a format the way you want it to be.