Difference between sortBy and orderBy in Laravel

November 9th, 2022

Sorting data in Laravel: sort by or order by

First, you need to understand the difference between a Collection object and a Builder object in Laravel.

OrderBy is a method that you can use on Builder object (Eloquent or Query), that is before you retrieve data from the database (before →get(), all(), find(), first(), ... methods). It is planning out a query from the database that has not yet run.

SortBy is a Laravel collection method that can be used on the Collection object, which you get after you finish the query (after →get(), all(), find(), first() method). It will sort the result of the query.

1// This is a Query (Builder object) that hasn't run yet
2// orderBy is used before retrieved data from database
3$posts = Post::with('category')->orderBy('title', 'ASC');
4 
5// Now the query has run. $posts is now a collection.
6$posts->get();
7 
8// You can sort $posts collection with laravel sortBy collection method (after ->get())
9$sorted_posts = $posts->sortBy('category.name');

orderBy() method is much more efficient than the sortBy(), it is faster for large number of data.

Related Posts