Skip to content
Advertisement

Laravel Eloquent, group by week and display start and end of week

I have the following code, which return a collection of Orders grouped by week.

return $order = Order::all()
        ->groupBy(function($date) {
            return Carbon::parse($date->created_at)->format('W'); //Grouping by week
        });

The result is the following, with, Obviously “05” being the week number.

{
 "05": [
  {
   "id": 5,
   "user_id": 1,
   "invoice_number": "2021",
   "notes": null,
   "total_paid": null,
   "payment_method": null,
   "deleted_at": null,
   "created_at": "2021-02-06T06:53:03.000000Z",
   "updated_at": "2021-02-06T06:53:03.000000Z"
  },
  {
   "id": 7,
   "user_id": 1,
   "invoice_number": "2021",
   "notes": "sadasdfasdsa daeqweq",
   "total_paid": null,
   "payment_method": null,
   "deleted_at": null,
   "created_at": "2021-02-06T07:10:45.000000Z",
   "updated_at": "2021-02-06T07:10:45.000000Z"
  },
  {
   "id": 8,
   "user_id": 1,
   "invoice_number": "2021",
   "notes": null,
   "total_paid": null,
   "payment_method": null,
   "deleted_at": null,
   "created_at": "2021-02-06T07:36:41.000000Z",
   "updated_at": "2021-02-06T07:36:41.000000Z"
  },
 ]
}

But to the proyect i’m currently working this is not the way I want to show it. Is there any way to display or return the week start and week end and not the week number? Like this

{
     "01-02-20201 - 07-02-2021": [
      {
       "id": 5,
       "user_id": 1,
       "invoice_number": "2021",
       "notes": null,
       "total_paid": null,
       "payment_method": null,
       "deleted_at": null,
       "created_at": "2021-02-06T06:53:03.000000Z",
       "updated_at": "2021-02-06T06:53:03.000000Z"
      },
      {
       "id": 7,
       "user_id": 1,
       "invoice_number": "2021",
       "notes": "sadasdfasdsa daeqweq",
       "total_paid": null,
       "payment_method": null,
       "deleted_at": null,
       "created_at": "2021-02-06T07:10:45.000000Z",
       "updated_at": "2021-02-06T07:10:45.000000Z"
      },
      {
       "id": 8,
       "user_id": 1,
       "invoice_number": "2021",
       "notes": null,
       "total_paid": null,
       "payment_method": null,
       "deleted_at": null,
       "created_at": "2021-02-06T07:36:41.000000Z",
       "updated_at": "2021-02-06T07:36:41.000000Z"
      },
     ]
    }

Advertisement

Answer

Yes, with Carbon it is easy to find the start and end of week.

->groupBy(function($date) {
    $created_at = Carbon::parse($date->created_at);
    $start = $created_at->startOfWeek()->format('d-m-Y');
    $end = $created_at->endOfWeek()->format('d-m-Y');
    
    return "{$start} - {$end}";
})
Advertisement