Let's say you're reviewing request metrics stored in your database, and one of the fields tracked is the device operating system. You have values like "macOS" and "Windows".
If you were to sort your query results by this field, which value would you expect to be sorted first?
The answer depends on case sensitivity, and that is influenced both by your database engine and the collation settings of your table or column.
I typically use MySQL with the utf8mb4_unicode_ci
collation, which is case-insensitive.
In this case, "macOS" would be sorted before "Windows" because the comparison ignores case.
Here's another wrinkle: what if your use case makes it more efficient to sort the results in Laravel/PHP, not in the database?
The Laravel collection sortBy
method is case-sensitive by default.
So, if you were to sort the same values using sortBy
, "Windows" would come before "macOS" because the ASCII character code for "W" is 87 and "m" is 109.
To the average user, they would likely view this case-sensitive ordering as a bug.
To avoid the possible complaint and perform a case-insensitive sort in Laravel, you can use the sortBy
method with a callback that normalizes the case:
$sorted = $collection->sortBy(function ($item) {
return strtolower($item->device_os);
});
Here to help,
Joel
P.S. Want development help from someone who cares about a consistent user experience? We can help!