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

makapaka's avatar

Merge collections and sort by date field

I have two collections that I am merging

    $model1 = $model1::where('week', 11)->get();
    $model2 = $model2::where('week', 11)->get();
    $all = $model1->merge($model2);

Once merged, I'm trying to sort by a start time in this format

{
0: {
   id: 106,
   start: "2018-06-14 13:50:00",
 },
 1: {
    id: 107,
    start: "2018-06-11 19:50:00",
  ....

It seems Laravel collection helper doesn't know how to sort this format using

$sorted = $all->sortBy('start');

Is there a way to convert it on the fly using the helper ?

0 likes
1 reply
makapaka's avatar
makapaka
OP
Best Answer
Level 7

This can be deleted - weird but for some reason this doesn't work

return response()->json($all->all());

But adding ->values() fixed it ?

return response()->json($all->values()->all());

Please or to participate in this conversation.