Sorting not working as expected for collection

Running into an odd issue where a collection of mine isn’t sorting by two fields which both of them share. Below is the code in question thus far.

return function($site, $pages, $page) {
    // send the XML header
    // Features
    $features = $pages->find('features/2016')->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(10);
    // [News]
    $news = new Pages();
    $newsFiltered = $pages->find('news/'.date('Y').'/'.date('m'))->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(10);

    if (sizeof($newsFiltered) > 0) {

    if (count($newsFiltered) < 11) {
        $newsFiltered_Previous = $pages->find('news/'.date('Y', strtotime('-1 month')).'/'.date('m', strtotime('-1 month')))->children()->visible()->sortBy('date', 'desc', 'time', 'desc')->limit(11 - count($newsFiltered));
    // generate the combined RSS feed
    $feed = new Pages();
    // order the combined RSS feed
    $feed->sortBy('date', 'desc', 'time', 'desc')->limit(10);
    // pass the variables back to the template
    return compact('feed');

Looking at the result, both the sortBy() and limit() on $feed aren’t taking effect. There’s some slightly differences in the blueprints, but the date and time fields both exist in each of them. So in theory there shouldn’t be any issue then you’d think.

Any ideas what the issue could be?

sortBy and limit don’t change the collection, they return a sorted / limited copy of the collection.

So, just assign the result to your $feed variable like this:

$feed = $feed->sortBy('date', 'desc', 'time', 'desc')->limit(10);
1 Like

Ah, that makes sense now with how it was behaving before — it’s working as expected after that fix.

Thanks! :slight_smile: