How to sort a collection in laravel?

by scotty_walker , in category: PHP Frameworks , 6 months ago

How to sort a collection in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 2 months ago

@scotty_walker 

In Laravel, you can use the orderBy method to sort a collection. Here is an example of how to sort a collection by a specific column in ascending order:

1
$users = User::orderBy('name')->get();


If you want to sort the collection in descending order, you can pass a second argument to the orderBy method like this:

1
$users = User::orderBy('name', 'desc')->get();


You can also sort the collection by multiple columns by chaining multiple orderBy methods like this:

1
$users = User::orderBy('name')->orderBy('created_at', 'desc')->get();


Additionally, you can use the sortBy method to sort the collection in memory. This method will not modify the original collection but return a new collection sorted by the specified attribute:

1
$users = $users->sortBy('name');


These are some of the ways you can sort a collection in Laravel.