Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Is there a non-case sensitive way to sort a collection by an attribute?

I'm struggling to sort an Eloquent collection using the sortBy() method. The issue is that the sorting is case sensitive and it first retrieves the uppercase results and then the lowercase ones, but what I'm trying to achieve is to sort every item no matter if it's uppercase or lowercase.

like image 374
Eseth Avatar asked Mar 21 '17 10:03

Eseth


People also ask

Is laravel case sensitive?

Laravel Routing Case-insensitive routes will match a GET request to /login but will not match a GET request to /Login . In order to make your routes case-insensitive, you need to create a new validator class that will match requested URLs against defined routes.


2 Answers

sortBy() second argument allows you to set some flags regarding on how the sorting should be handled.

Flags are exactly the same as PHP sort() native function.

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

source: php.net

You could try by using $collection->sortBy('key', SORT_NATURAL|SORT_FLAG_CASE).

like image 176
GiamPy Avatar answered Sep 30 '22 16:09

GiamPy


If you have a simple list of values and want to sort them ignoring the case, you can also use sort() instead of sortBy() with a callback function like so:

$collection->sort(function($a, $b){
    return strtolower($a) <=> strtolower($b);
});
like image 38
maesk Avatar answered Sep 30 '22 15:09

maesk