Laravel's Collection
class (v5.5) has a sortBy()
method that sorts everything similar to if you had used a SQL ORDER BY
statement, except there is one striking difference: a relational database will put NULL
values at the end when sorting ascending (or at least PostgreSQL does), but Laravel's sortBy()
method puts NULL
values first.
So how do I get those NULL
values to be sorted last instead of first when using the Collection::sortBy()
method? PLEASE NOTE: I cannot change the database query itself! MY ONLY OPTION is to sort the Collection itself within PHP. I absolutely cannot do this at the database level in my situation.
There is a similar question on Stack Overflow here but the solution OP found was kind of a hack and does not work in my situation, because I need it to work for varchars.
NOTE: I realize sortBy()
accepts a Closure for the first argument but there is zero explanation in the documentation about the arguments this closure receives (which "key" is $key
?), nor does it explicitly say what the closure is supposed to return in order to determine the sort order. (I'm assuming it should return an integer representing the order, but I do not know how to make that work for me with multiple NULL
values.)