It seems like you're trying to sort a collection of Appt models by the appt_carbon attribute, which is a Carbon instance. The sortBy method should work correctly for this purpose, assuming that appt_carbon is a date or datetime field. However, if the appointments are not sorting as expected, there might be an issue with the collection being modified after the sort operation or the sort operation not being applied correctly.
Here's a revised version of your code that ensures the sorted collection is reassigned back to $oh->appts:
public function getApptBookButtons($t, $oh, $date) {
foreach($t as $type => $times) {
foreach($times as $time) {
$slot = new Appt([
'appt_carbon' => new Carbon($date->format('Y-m-d').' '.$time->format('H:i:s')),
'appt_date' => $date->format('Y-m-d'),
'appt_time' => new Carbon($date->format('Y-m-d').' '.$time->format('H:i:s')),
'appt_type_id' => $type,
'doctor_id' => $oh->doctor_id,
'officehour_id' => $oh->id,
'appt_note' => $type !== 2 ? '<br /> NEW PATIENT' : null,
]);
// Push the new slot into the appointments collection
$oh->appts->push($slot);
}
}
// Sort the appointments collection by the 'appt_carbon' field
$sortedAppts = $oh->appts->sortBy(function ($appt) {
return $appt->appt_carbon;
});
// Reassign the sorted collection back to $oh->appts
$oh->appts = $sortedAppts->values(); // Calling values() to reset the keys after sorting
}
A few things to note:
- The
sortBymethod returns a new sorted collection, so you need to reassign it back to$oh->appts. - After sorting, it's a good practice to call
values()on the collection to reset the keys. This ensures that the collection is reindexed and can prevent issues when converting the collection to JSON or when iterating over it. - Ensure that the
appt_carbonfield is indeed a Carbon instance and that it's formatted correctly for comparison.
If you're still facing issues, you might want to double-check the contents of the appt_carbon field to ensure that they are valid Carbon instances and that they are comparable. You can also add some logging or dd() statements to inspect the collection before and after sorting to verify that the sorting is being applied as expected.