logo
podcast Podcast
get help Get Unstuck

Use PHP sorting flags with Laravel collections

Combining PHP and Laravel is powerful

Joel Clermont
Joel Clermont
2025-09-11

In an earlier tip on sorting, I showed the following code example to use case-insensitive logic when sorting a Laravel collection:

$sorted = $collection->sortBy(function ($item) {
    return strtolower($item);
});

Someone pointed out to me that you could also use PHP's built-in sorting flags to accomplish the same thing.

I have used these flags many times with PHP's built-in array and sort functions, but I somehow missed that Laravel supported them as well, so I wanted to share with you.

Here's what the same code would look like using the flags:

$sorted = $collection->sort(SORT_FLAG_CASE | SORT_NATURAL);

I like this because it uses built-in PHP functionality.

Here to help,

Joel

P.S. Just as with this sorting example, there is often more than one way to do something. That's why it is valuable to get a variety of opinions in the Mastering Laravel community.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.