0

I've got a little problem with my Laravel controller and sorting it:

public function index()
{
    $achievements = Achievement::all();
    $news = News::all();
    $livingspaces = Livingspace::all();
    $therapies = Therapy::all();
    $events = Event::all();
    $collection = collect();

    foreach ($achievements as $achievement) {
        $collection->push($achievement);
    }
    foreach ($news as $new) {
        $collection->push($new);
    }
    foreach ($livingspaces as $livingspace) {
        $collection->push($livingspace);
    }
    foreach ($events as $event) {
        $collection->push($event);
    }
    foreach ($therapies as $therapy) {
        $collection->push($therapy);
    }

    $sortedData = $collection->sortBy('category')->sortByDesc('created_at');
    return response()->json([
        'sortedData' => $sortedData
    ], 200);
}

It's not sorting at all. It should sort if after the data in the created_at timestamp which comes out of the box when creating a new migration for a Laravel controller. But I can't sort the data. I think it has something to do with pushing the data from the DB directly into the collection and it's not looking for "created_at" at all. It's not giving any errors or anything its just not doing anything. The same goes for sortBy.

n1ghty
  • 19
  • 9

1 Answers1

0

sortByDesc method has the same signature as the sortBy method, but will sort the collection in the opposite order. By default sortBy to do the ascending operation. If you want to sort by decending:

$sortedData = $collection->sortBy('category', true);
dhamo dharan
  • 712
  • 1
  • 10
  • 25