Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

How to sort a collection by multiple attributes : user_name then by date and then by quarter

Hello,

I want to export a collection to excel but first I want to sort by :

user_name then by date then by quarter as you can see bellow

Illuminate\Support\Collection {#1603 ▼
  #items: array:5 [▼
    0 => {#1443 ▼
      +"user_id": 172
      +"user_name": "David Hervy"
      +"date": "2022-09-30"
      +"quarter": "Q4"
    }
    1 => {#1473 ▼
      +"user_id": 172
      +"user_name": "Sandra Tuner"
      +"date": "2022-09-30"
      +"quarter": "Q3"
    }
    2 => {#1459 ▶}
    3 => {#1476 ▶}
    4 => {#1626 ▶}
  ]
  #escapeWhenCastingToString: false
}

It works if I sort only by user_name and quarter

        return Excel::download(new InsightsPlanningExport(
            collect($queryEmptyDates)->merge($this->plannings->get())
            ->sortBy([
                ['user_name','asc'],
                ['quarter','asc'],
            ])
        ), 'file_name.xlsx');

BUT if I add date :

        return Excel::download(new InsightsPlanningExport(
            collect($queryEmptyDates)->merge($this->plannings->get())
            ->sortBy([
                ['user_name','asc'],
                ['date','asc'],
                ['quarter','asc'],
            ])
        ), 'file_name.xlsx');

It returns Error : date() expects parameter 1 to be string, object given

0 likes
7 replies
vincent15000's avatar

Not sure at all, but could it a casting problem on the date ?

GodziLaravel's avatar

@vincent15000 No it will sortBy the latest one only and me I want first sort by user_name then by date then by quarter

1 like
vincent15000's avatar

@GodziLaravel Have you thought about sorting the data directly in the database query ? It's much faster than sorting a collection.

vincent15000's avatar

@GodziLaravel Can you just try this please ?

dd(collect($queryEmptyDates)->merge($this->plannings->get())
    ->sortBy([
    	['user_name','asc'],
    	['date','asc'],
    	['quarter','asc'],
]);

And perhaps also this one.

dd(collect($queryEmptyDates)->merge($this->plannings->get())
    ->sortBy([
    	['date','asc'],
]);

Please or to participate in this conversation.