roemer
2 years ago

Collection sortBy doesn't actually sort

Posted 2 years ago by roemer

Hi, I'm trying to sort some objects. These objects are realestate properties, and can be sorted in multiple ways. These are the options:

  • price_low
  • price_high
  • random
  • oldest
  • newest

When I want to order by price though (with Collection::sortBy()), it doesn't actually sort. Here's my code.

                switch($filter->order_by)
                {
                    case 'price_low':
                        $filter->properties = $filter->properties->sortBy(function($property)
                        {
                            return $property->price;
                        });
                        break;
                    case 'price_high':
                        $filter->properties = $filter->properties->sortByDesc(function($property)
                        {
                            return $property->price;
                        });
                        break;
                    case 'oldest':
                        $filter->properties = $filter->properties->sortBy(function($property)
                        {
                            return $property->created_at;
                        });
                        break;
                    case 'newest':
                        $filter->properties = $filter->properties->sortByDesc(function($property)
                        {
                            return $property->created_at;
                        });
                        break;
                    case 'random':
                        $filter->properties = $filter->properties->shuffle();
                        break;
                }

As you can see, a Filter has an order_by property, which sorts the properties in it's properties property. The sortBy method does run, but the properties still appear completely random, and not sorted by price. I'd give an example of this but it's a huge amount of (classified) content, but it's definitely random.

Any idea what's going wrong?

Please sign in or create an account to participate in this conversation.