How to Sort the Order of a Collection in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the table of contents of Laravel articles
This article summarizes how to sort the order of a collection in Laravel.
Laravel Framework 8.83.8
Vue 2.6
Conclusion
// Assuming you have a collection like this.
$posts = Post::all();
// Sort
$sorted = $posts->sortBy('created_at');
// Remove keys
$sorted->values()->all();
Explanation
In this example, let's try changing the order of a collection that was obtained from the Posts table.
Ascending order of created_at
$sorted = $posts->sortBy('created_at');
In this state, you will see by using dd() that keys are present, making it difficult to simply use it in a foreach loop.
It seems like keys are associated with the collection before sorting. Currently, the purpose of using these keys is unclear, so let's move on to the next point.
Remove keys and make it easier to use with the following code
$sorted->values()->all();
By using this code, the keys are removed, and the collection is now in a more user-friendly state.
When you want to sort the collection in descending order
$sorted = $posts->sortByDesc()('created_at');
Summary
That's all.
I hope this can be useful for someone.
For feedback or complaints, please contact me via Twitter DM.
Thank you!
Popular Articles
Deploying PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs